How to get the current directory in Python?
In this short tutorial, let us look at how you could use python to get the current directory and how to change the working directory.
In case you are here only for the solution of getting the current directory in Python, use this link.
Table of Contents
- What are directories and how do they work?
- Python get current directory
- Python change directory
- Limitations and Caveats
What are directories and how do they work?
In case you are new to programming, directories are nothing but folders. These directories are present inside a root folder eg:
D:\ and each directory could contain files or subdirectories.
To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you can view a particular file’s path by right-clicking the File-> Properties-> General-> Location.
Similarly, to run a script, the working directory needs to be set to the directory containing the script. However, while trying to run multiple scripts or while handling files the Current Working Directory (CWD) is important.
Python would not be able to access the files if they aren't in the CWD. It is in these scenarios that the Python ‘get current directory’ command helps you know which directory you are in currently.
Python get current directory:
To return the directory you are currently in, we use the OS module to interact with the operating system. Under the OS module, we use the
os.getcwd() method to return the path of the current directory.
Syntax of os.getcwd:
Code for python get current directory:
#importing the os module import os #to get the current working directory directory = os.getcwd() print(directory)
The output may vary depending on the directory you are in but it would start from the root folder eg:
D:\ and the directory prefixed by a
Python change directory
Similar to the
os.getcwd method we used in Python to get the current directory, we use the
chdir() methods in the os module to change the current directory.
The current directory is changed to retrieve files or run scripts that are present in other directories.
Syntax of chdir():
Parameters:path - The path to the new directory
Code to change current directory:Let's say I want to change the current directory to a subdirectory called "freelancer" that is present inside the "flexiple" directory.
import os os.chdir("C:\flexiple\freelancer")
Limitations and Caveats:
os.getcwdmethod only returns the current working directory, in case you want the entire path, use the
- Unlike the
os.getcwdthe change directory requires a parameter that needs to be a directory, if not, Python returns 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