How to get the path of the current directory in Python
In this tutorial, we are going to see how to get the path of the current directory in Python. The current directory is nothing else than the folder from where your script is executed.
How to get the path of the current directory in Python
To perform this task, we will use the “os” module in Python. It has a method called getcwd() which will return the current directory. It returns the full(absolute) path of the current working directory. If you just want the name of the directory, you can either separate it with “/” or use another function called “basename” from the “os.path” module.
Below is the code that returns the absolute path of the current directory and its name.
import os # get the path of the current directory path = os.getcwd() print("Path of the current directory : " + path) # get the name of the current directory repn = os.path.basename(path) print("Name of the current directory : " + repn)
Output:
Path of the current directory : /home Name of the current directory : home
Get the script path
Now let’s look at how to get the script path regardless of where you are running it. For that, we will use the special variable called __file__ and pass it to realpath() method of the os.path module.
import os # get the script path path = os.path.realpath(__file__) print("The script path is : " + path)
Output:
The script path is : /home/main.py