Skip to content
Related Articles

Related Articles

How to Get directory of Current Script in Python?
  • Last Updated : 26 Nov, 2020

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 does not require any installation.

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.  

We would be utilizing the dirname() function found within the os.path module extensively within the following examples. And therefore it would be better if we get acquainted about it beforehand.

Syntax: os.path.dirname(path)



Parameter:

path: A path-like object representing a file system path.

Return Type: 

This method returns a string which represents the absolute path to the parent directory for the specified path

Methods 1#: 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.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


OUTPUT:



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

Drawbacks:  

  • The above method would only work if it is used inside a python script. Therefore, if run from an interactive environment (stdin) or line by line interpreter (debugging) it would not work.
  • __file__ would not be present in statically linked C modules (libraries written originally in C but ported over to python)
  • __file__ would not be defined in a built-in module

Methods 2#: 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.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


OUTPUT:

C:\suga

Drawbacks:

  • The above method would only work if sys.argv[0] is used inside a python script. It won’t work for raw stdin, ex. running the command from the python command-line interpreter (IDLE).
  • The above method is argument based, therefore if the python script is run in a particular way such that the first argument (at index 0) is not the filename of the executable, the method won’t work. Ex. if the Lpath.py file is ran using the command  ‘py Lpath.py‘ it would result in no output being displayed.

Methods 3#: 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.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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. 

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :