Open In App

How to Get directory of Current Script in Python?

A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. 

In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about various uses/demerits of each. For performing the aforementioned task we would be using two libraries named os and inspect, both of which are built-in and therefore do not require any installation.

File Structure

For demonstration purposes, we would be using the following file, which is located at C:\suga\Lpath.py. The file’s content (code) will be changed according to the context in which it is being referenced.  

Method 1: Use the OS module to get the Home Directory using expanduser(‘~’)

This function is recommended because it works on both Unix and Windows. The Python os module offers an os.path.expanduser() to retrieve the home directory. This also functions if it is a shorter path, such as /Documents/my folder. 




import os
print(os.path.expanduser('~'))

Output:

C:\suga

Method 2: Use the OS module to get the Home Directory using home()

 The path.home() to get the home directory in Python. It returns a new path object having the user’s home directory.




from pathlib import Path
print(Path.home())

Output:

C:\suga

Methods 3: Using __file__ module object.

In this method, we would be using the __file__ (file keyword surrounded by double underscores (dunder)). This predefined attribute is present in most python files. This attribute is used for obtaining the filename of the currently executing python file. We would be passing the path obtained by __file__, to os.path.dirname() function in order to get the parent directory of the python file.




import os
 
# Displaying the script path
print(__file__)
 
# Displaying the parent directory of the script
print(os.path.dirname(__file__))

Output:

C:\suga\Lpath.py
C:\suga

Drawbacks:  

Methods 4: Using sys.argv[0] command-line argument

sys.argv is a list that contains the command line arguments passed to the python program. In this method we would be using the 0th argument of sys.argv list, that is the path to the current executing python file, to get the parent directory of the python script.




import sys
 
print(os.path.dirname(sys.argv[0]))

Output:

C:\suga

Drawbacks:

Methods 5: Using getsourcefile() function  

In this method we would be using the getsourcefile() method found inside the inspect library, to obtain the absolute path of the currently executing python script. Then we would be passing it to os.path.dirname() function to get the parent directory of the filename. This method is generally the most optimal and compatible one of the aforementioned methods as it is cross-platform, small scale (fewer code lines), and works under variable execution environments.  

Syntax: getsourcefile(object)

Parameters:

  • object: A Referenceable object within the python script

Return Type: Returns the full path to the file within whom the object was found.

 Returns None if the object could not be identified within the source.




from inspect import getsourcefile
 
import os
 
 
print(os.path.dirname(getsourcefile(lambda:0)))

Output:

C:\suga

Explanation:

Firstly, we imported the getsourcefile() function found inside the inspect library. After which we imported the os library for using the os.path.dirname() function found within, which would be used for extracting the parent directory out of the script filename. We provided lambda:0 as the argument to the getsourcefile() function, as it required a reference object within the python script, therefore we created a dummy function using lambda, just to enable it to be referenced within the python script.  

NOTE: The above code might have to be altered a bit (using a self-tailored function, rather than dirname()) if it is to be executed within line-by-line interpreters (ex. IDLE). But that is outside the scope of this article. 


Article Tags :