This short tutorial shows how to list and change the current working directory using Python. Python can be used to perform many actions on a file system, for example you can rename a file in Python, copy a file or delete a file and more. To do so, it’s first useful to understand how to get the current working directory and change to a different directory – essentially the Python equivalent of using the pwd
command and the cd
command.
Note: When you run a python script the working directory is the directory where the script has been executed from.
Get Current Working Directory in Python using os.getcwd()
In Python, the getcwd() method is used to list the current directory. This method is a part of the os module, which is the Python module generally used to interact with the operating system.
The syntax for using os.rename is simply:
os.getcwd()
Running getcwd
interactively looks like this:
>>> os.getcwd()
'/root'
The output is returned as a string.
Change Current Working Directory using os.chdir
We can change the current working directory using the chdir() method. For example, to change to the /tmp
directory we could use the following:
>>> os.chdir("/tmp")
If the directory doesn’t exist, or the user running the script doesn’t have the required permissions to access the directory then an error will be returned.
How to Use getcwd() and chdir() in a Python Script
So far we have seen examples of how to get the current working directory and how to change directory in Python interactively. Now, let’s take a look at an example of how these methods could be used in a Python script.
import os
print("The current working directory is: {0}".format(os.getcwd()))
os.chdir('/usr')
print("The current working directory is: {0}".format(os.getcwd()))
This short script first imports the OS module, then prints the current working directory, before changing the working directory to /usr
, before confirming the new current working directory.
Final Thoughts
In this short tutorial you have learned how to use the OS module in Python to get the current working directory using the getcwd()
method and how to change directory using the chdir()
method.