Techibee.com

Get current directory using Python

In today’s post we will see how to find current directory(or working directory) using python. Current directory is nothing but the folder from where your script is running. This is not the path where your py script is located, but we will explore how to find it as well.

Get the path of current working directory

To accomplish this task we will use os module in python. It has a method called getcwd() which will return current working directory. It is that simple. It returns full path(absolute) of the current working directory. If you want just the directory name then either you can split by “/” or use another function called basename from os.path module.

Below is the code that returns both absolute path of the current working directory and its name.


import os

dirpath = os.getcwd()
print("current directory is : " + dirpath)
foldername = os.path.basename(dirpath)
print("Directory name is : " + foldername)

Copy the above code into a file and save it as get_path.py and run it to see the results.

As you can see in the above screen, the script(get_path.py) is stored in python directory. When ran this script from same directory as script it returned the directory name as python. Same script when ran from another directory(Documents) using relative path, it returned the directory name as Documents. So it always returns the current working directory from where your script is triggerred.

Get the path of script file

Now let us see how to get the path of script it self irrespective of from where you are running it. For this purpose we will utilise the special variable called __file__ and pass it to realpath method of os.path module.


import os

dirpath = os.getcwd()
print("current directory is : " + dirpath)
foldername = os.path.basename(dirpath)
print("Directory name is : " + foldername)
scriptpath = os.path.realpath(__file__)
print("Script path is : " + scriptpath)

Copy the above code into a file and execute it to see the results. In the below demonstration, I have executed it from another directory using the relative path and you see that script location is being displayed properly.

As you can see in the screenshot, the script path is being displayed.

Hope this helps and stay tuned for more.

Exit mobile version