- Python: Get and Change the Working Directory
- What is the Python os Library
- Get the Working Directory with Python OS
- Change the Working Directory with Python OS
- Handling Error Codes with Python OS
- Conclusion
- Related Articles
- Python Get Current Directory – Print Working Directory PWD Equivalent
- How to Get The Current Directory Using the os.getcwd() Method in Python
- How to Get The Current Directory Using the Path.cwd() Method in Python
- Conclusion
Python: Get and Change the Working Directory
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()
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.
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:
Python Get Current Directory – Print Working Directory PWD Equivalent
Dionysia Lemonaki
In this article, you will learn how to get the current working directory (another name for folder) in Python, which is the equivalent of using the pwd command.
There are a couple of ways to get the current working directory in Python:
- By using the os module and the os.getcwd() method.
- By using the pathlib module and the Path.cwd() method.
How to Get The Current Directory Using the os.getcwd() Method in Python
The os module, which is part of the standard Python library (also known as stdlib), allows you to access and interact with your operating system.
To use the os module in your project, you need to include the following line at the top of your Python file:
Once you have imported the os module, you have access to the os.getcwd() method, which allows you to get the full path of the current working directory.
Let’s look at the following example:
import os # get the current working directory current_working_directory = os.getcwd() # print output to the console print(current_working_directory) # output will look something similar to this on a macOS system # /Users/dionysialemonaki/Documents/my-projects/python-project
The output is a string that contains the absolute path to the current working directory – in this case, python-project .
To check the data type of the output, use the type() function like so:
print(type(current_working_directory)) # output #
Note that the current working directory doesn’t have a trailing forward slash, / .
Keep in mind also that output will vary depending on the directory you are running the Python script from as well as your Operating System.
How to Get The Current Directory Using the Path.cwd() Method in Python
In the previous section, you saw how to use the os module to get the current working directory. However, you can use the pathlib module to achieve the same result.
The pathlib module was introduced in the standard library in Python’s 3.4 version and offers an object-oriented way to work with filesystem paths and handle files.
To use the pathlib module, you first need to import it at the top of your Python file:
Once you have imported the pathlib module, you can use the Path.cwd() class method, which allows you to get the current working directory.
Let’s look at the following example:
from pathlib import Path # get the current working directory current_working_directory = Path.cwd() # print output to the console print(current_working_directory) # output will look something similar to this on a macOS system # /Users/dionysialemonaki/Documents/my-projects/python-project
As you can see, the output is the same as the output I got when I used the os.getcwd() method. The only difference is the data type of the output:
print(type(current_working_directory)) # output #
Conclusion
And there you have it! You now know how to get the full path to the current directory in Python using both the os and pathlib modules.
Thanks for reading, and happy coding!