How to Get and Change the Current Working Directory in Python?

Python change working directory: This article will detail how to get the current working directory and how to change the working directory in python.
How are the directories defined?
For beginners in programming, a directory is nothing more or less than a folder. These directories are contained in the root (often noted C:/ or D:/ depending on how many hard disks you have). A directory usually contains files or subdirectories.
In your python project, you may have to navigate between several directories so it is important to know the exact path to these directories. To run a script, the working directory must be defined as the one that contains the script to run. If you have several scripts in different directories, the current working directory (CWD) is very important.
Under Windows, you can know the path of a file by right-clicking on the file then properties then General then Location. Under Linux, you can use the shell with the command pwd for example.
In the rest of this tutorial, we will see how to get the current working directory and also how to change it directly in python.
Python Get Current Directory: os.getcwd()
To get the current working directory (CWD), the OS module in python provides us a method called os.getcwd() :
import os
# Get the current working directory
directory = os.getcwd()
print(directory)
Output:
C:\Users\amiradata\Pycharm\projects1
os.getcwd() returns the absolute path of the current working directory as a string str. For users familiar with Unix, this is equivalent to the pwd command.
Python Change Current Directory: os.chdir()
You can change the current working directory with the os.chdir() method also present in the OS module.
This method allows you to specify the destination path. This path can be absolute or relative (../ to move up ).
In Unix, the equivalent is the cd command.
Here are two examples of use:
import os
# change the current directory
os.chdir("C:/Users/amiradata/Pycharm")
print(os.getcwd())
Output:
C:/Users/amiradata/Pycharm
import os
# change the current directory with ../..
os.chdir("../..")
print(os.getcwd())
Output:
C:/Users/amiradata
The second example allows to move up 2 levels.
Handling the Errors While Changing the Directory
When the given path in argument of the os.chdir() method does not exist, it will generate a runtime error: FileNotFoundError. To prevent your script from crashing, it is important to handle the exception with the try/except statement.
import sys, os
cwd = os.getcwd()
dirchange = 'C:/Users/amiradata/Pycharm/Project_Python'
try:
print("Change current directory")
os.chdir(dirchange)
except:
print("{} : Directory doesn't exist or something wrong..".format(dirchange))
print(sys.exc_info())
finally:
os.chdir(cwd)
print("Current directory is ", os.getcwd())
Output:
Change current directory
C:/Users/amiradata/Pycharm/Project_Python : Directory doesn't exist or something wrong..
(<class 'FileNotFoundError'>, FileNotFoundError(2, 'Le chemin d’accès spécifié est introuvable'), <traceback object at 0x000001372795C408>)
Current directory is C:\Users\ayed7\Pycharm\projects1
Python Change Current Directory: Limitations and Warnings
- os.chdir() only takes a directory as parameter. You cannot specify the full path of a file or it will raise a NotADirectoryError exception.
- os.getcwd()returns only the current working directory. Use the os.path.realpath(file) method to get the full directory.
- If you do not have permissions to access the directory, a 1PermissionError exception is raised.
- As described above, if the given directory does not exist, a FileNotFoundError exception is raised.
Conclusion
In this article, we have seen how to modify and get the current working directory using the python OS module.
If you have any doubt or question about the use of a method mentioned in this tutorial, don’t hesitate to tell me in comments.
Comments
Leave a comment