If you have worked on a Python application where you had data in another folder, you would have used a command-line tool like cd
to change directories. In this tutorial, we will learn a more Pythonic way of changing directories.
Changing directories using the os.chdir function
The easiest way to change the working directory in Python is importing the os
package and calling the chdir()
function. The function takes in the target directory as an input parameter
Let us see an example
- Get the current working directory
Let us first see the current working directory in Python. We can achieve this by calling the os.getcwd()
function
import os os.getcwd()
We get the following output when we execute the above two lines
/content
- Get the contents of the current working directory
Β We will now execute the function call to get the contents of the working directory. We can do this by calling the following function in Python
os.listdir()
We get the following output
['.config', 'sample_data']
- Navigate to target directory
We will now use the os.chdir()
function to navigate to the βsample_dataβ
directory
os.chdir('sample_data')
We can now again call the os.getcwd()
function to verify if the directory was changed.
os.chdir('sample_data')
We get the following output
/content/sample_data
Changing the Working Directory using Context Manager
The second approach to change the working directory is using a context manager. Let us see an example and the benefits of using a context manager.
In the previous example, the working directory changes even outside a function. Most of the time, we would want to run out logic inside a function and once we exit the function, we would like to return the previous working directory. A context manager helps us to achieve this without any errors
- Import the libraries
Let us first import the libraries
from contextlib import contextmanager import os
- Function to change directories
We will now implement a function call change_path()
using the @contextmanager
decorator function.
@contextmanager def change_path(newdir): old_path = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: yield finally: os.chdir(old_path) ο»Ώ
- Call the function change_path
with change_path('sample_data'): print(os.getcwd())
We get the following output
/content/sample_data
If we now call the os.getcwd()
we get the following output
/content
As you can see outside the context of change_path we are in the previous directory. We can do the processing by changing the directory inside the context of the change_path function
Summary
In this tutorial we looked at two ways to change the working directory in Python.
- Using
getcwd()
we can change the directory, but the directory is changed also outside the scope of a function - Using
contextmanager
we can change the directory in an error-free manner and outside the context of a function, the directory is not changed.