Skip to content

Python: Get and Change the Working Directory

Python Get and Set Current Working Directory Cover Image

In this tutorial, you’ll learn how to use Python to get and change (set) the working directory. Being able to work with the file system is a great skill to learn for a Python developer of any skill level. Being able to get and to change the working directory while in a Python script allows you to easily work with relative paths. This allows you to easily write paths to that are relative to the working directory.

By the end of this tutorial, you’ll have learned:

  • An overview of working with working directories using the Python os library
  • How to use the Python os library to get the working directory
  • How to change the working directory with Python
  • How to troubleshoot different error codes like NotADirectoryError or FileNotFoundError errors

Being able to work with and move around file systems is an important skill. This is especially true in data science where you may have directories for data, models, and scripts. Being able to traverse these directories without using paths fixed to a given computer allows you to build more flexible code that can move across computers.

The Quick Answer: Use os.getcwd() and os.chdir()

Quick Answer - Get and Change Working Directory Python
How to get and set a working directory in Python

What is the Python os Library

The Python os module a built-in library allows us to perform common operating system tasks. Because the library is built into Python, you can easily import is directly, such as shown below:

# Importing the os Module
import os

The module abstracts a number of helpful operating system operations. This is particularly helpful when developing scripts that are intended to work across different operating systems. The os module has a number of helpful functions. For example, it can be used to copy files using Python or to delete files using Python.

Python Get and Set Working Directory Snapshot
The key functions to use to get and change your current working directory in Python

Get the Working Directory with Python OS

In this section, you’ll learn how to use the os library to get the current working directory in Python. By knowing the working directory, we can files in the directory by using relative paths. This allows us to build scripts that can easily move from one system to another, as long as the relative directory is the same.

We can use the Python os .getcwd() function to get the current working directory. getcwd stands for get current working directory.

Let’s see what this looks like:

# Get Current Working Directory with os.getcwd()
import os
cwd = os.getcwd()

print('Current Working Directory is: ', cwd)
# Returns: Current Working Directory is:  /Users/datagy

The function doesn’t accept any arguments and returns a unicode representation of our current working directory. The format of the outputted directory will, of course, vary from operating system to operating system. In the above example, I’m running on a the script on a Mac OS computer. On a Windows computer, you may encounter a result such as C:\Users\datagy\Documents.

If you want to find the path to the file that is currently running your code (meaning you get the path to directory as well), you can use the os library as well. Simply assign os.path.realpath(__file__) to a variable and you can access it. The __file__ variable is used to identify the current file being imported.

Now that you know how to get the current working directory in Python, let’s see how we can use it change (or set) the working directory.

Change the Working Directory with Python OS

The Python os library comes with a helpful function that works similar to the getcwd() function. The chdir() function allows us to change the working directory. Unlike the getcwd() function, this function does accept a parameter and doesn’t return anything.

We can pass in either an absolute path or a relative path. Passing in an absolute path gives us the benefit of being explicit about where we want to change our working directory to. Using a relative path affords us the ability to reuse our script across different file systems, without knowing exactly where the script is running from.

Let’s see how the function works by using Python to change a working directory using an absolute path:

# Change the current working directory with os.chdir()
import os
cwd = os.getcwd()
print('Current Working Directory is: ', cwd)

absolute_path = '/Users/datagy/Documents'
os.chdir(absolute_path)

print('New working directory is: ', os.getcwd())

# Returns:
# Current Working Directory is:  /Users/datagy
# New working directory is:  /Users/datagy/Documents

The example above is a bit verbose: really, you just need to call os.chdir(absolute_path). However, I wanted to illustrate how the changing of directories could work.

Now, let’s take a look at changing working directories using relative paths in Python. To move up a folder with a relative path you can simply use ../, while moving down in the current directory involves simply adding that directory name into the script.

Let’s take a look at an example where we move down into a directory and then use relative paths to move back up:

# Change the current working directory with os.chdir()
import os
print('Current Working Directory is: ', os.getcwd())

# Move down a directory to 'Documents'
os.chdir('Documents')

# Confirm the current directory
print('Current Working Directory is: ', os.getcwd())

# Use relative paths to move up a directory
os.chdir('../')

# Confirm the current directory
print('Current Working Directory is: ', os.getcwd())

# Returns:
# Current Working Directory is:  /Users/datagy
# Current Working Directory is:  /Users/datagy/Documents
# Current Working Directory is:  /Users/datagy

We can see here that we used relative paths to move down a directory and then back up. This allows us to take this code from computer to computer – as long as the directory structure exists, the program will run without fail. Check out this tutorial to learn how to check if a file or directory exists in Python.

Handling Error Codes with Python OS

Working with file systems is never easy. There is plenty of room for typos to be made or user error that accidentally removes a directory that your code depends on. When changing a directory, the os.chdir() function expects a directory as its input. If, for example a file is passed in, then Python will raise a NotADirectoryError.

If you attempt to traverse the file system to a directory that doesn’t exist, then a FileNotFoundError (or an IOError) is raised. If you do not have sufficient permissions to move into a directory, Python will raise a PermissionError.

Being aware of these errors codes and why they occur is an important process. It allows you to be more prepared in troubleshooting your programs and finding ways to solve your errors.

Conclusion

In this tutorial, you learned how to use Python to get a current working directory and how to use it to set a working directory. Being able to work with file systems and moving between directories allows you to built programs with growing complexity. This can be particularly important in data science when you’re working with directories that contains scripts and directories that contain data. It allows you to organize your files into logical directories that complement the set up of your program.

To learn more about the Python os library, check out the official documentation here.

Related Articles

Check out the articles below to learn about similar topics:

Leave a Reply

Your email address will not be published.