In this python tutorial, we look at how you can get the current working directory in Python and how you can change the working directory.
- What are directories and how do they work?
- Python get current directory
- Python change directory
- Limitations and Caveats
In case you are new to programming, directories are nothing but folders. These directories are present inside a root folder eg:
C: \ or
D: \ and each directory could contain files or subdirectories and so on. And to retrieve a file from you would need to know the exact path to reach the file, in windows you can view a particular file path by right-clicking the file-General-Location.
Furthermore, when you run a python script, the current directory is set to the location of the script. And, while trying to run another script or while handling files in python the Current Working Directory (CWD) is important as python would not be able to access the files if there aren't in the CWD. It is in these scenarios that the python get current directory helps you know which directory you are in currently.
The python get current directory would help you know which directory you are currently in, to do this we use the OS module to interact with the operating system and we use the
os.getcwd() method to return the path of the current directory.
#importing the os module import os #to get the current working directory directory = os.getcwd() print(directory)
The output way may vary depending on the directory you are in but it would root folder eg:
D: \ and the directory prefixed by a
Similar to python get current directory we use the os module to change the current directory as well. We make use of the
chdir() methods to change the directory. Uses of this would again be to change the current directory in order to retrieve relevant files.
path - The path to the new directory
Let's say i wanted to change the directory to a directory called "freelancer" inside the "flexiple"
import os os.chdir("C:\freelancer\flexiple")
- The python get current directory method only return the current working directory, in case you want the entire path, use
- Unlike the python get current directory the change directory requires a parameter that needs to be a directory, and if not python return a
- If the directory does not exist then a
FileNotFoundErroris returned. And in case the user lacks the necessary permissions to access the directory a
Do let me know your thoughts in the comment section below. Happy coding :)