The Wayback Machine - https://web.archive.org/web/20240720142956/https://www.geeksforgeeks.org/how-to-get-directory-of-current-script-in-python/
Open In App

How to Get directory of Current Script in Python?

Last Updated : 02 Aug, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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. 

Python3




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.

Python3




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.

Python3




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:  

  • 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 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.

Python3




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


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 an 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 run using the command  ‘py Lpath.py‘ it would result in no output being displayed.

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.

Python3




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. 



Similar Reads

Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
Get Current directory in Python
In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The concept of the Current Working Directory (CWD) becomes
3 min read
Change current working directory with Python
The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by
2 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir() functionUsing glob() functions Method 1: Using o
3 min read
Python - Get list of files in directory with size
In this article, we are going to see how to extract the list of files of the directory along with its size. For this, we will use the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent f
9 min read
Get sorted file names from a directory by creation date in Python
In this article, we will understand how to retrieve sorted file names from a directory using Python. For this, we would make use of the Python glob library's glob function. There is no need to install this module externally because it is already included with Python. Firstly, The glob function would be used to obtain the list of files/directories w
3 min read
Get Location of Python site-packages Directory
A Python installation has a site-packages directory inside the module directory. This directory is where user-installed packages are dropped. A .pth file in this directory is maintained, which contains paths to the directories where the extra packages are installed. In this article, you will learn how to find the location of Python's site-packages
2 min read
Get current date using Python
Prerequisite: DateTime module In Python, Date and Time are not data types of their own, but a module named DateTime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. The DateTime module provides some functions to get the current date as well as time. Get the
2 min read
Get current time in milliseconds using Python
In this article, we will get the time in milliseconds using Python. Here, we are using two inbuild modules of Python that is Datetime module and the Time Module to get the time in milliseconds. Get time in milliseconds using the DateTime module To get the time in milliseconds we used the DateTime module, Firstly we printed the date time with second
2 min read
How to Get Current Date and Time using Python
In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python. Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleIn this example, we will learn How to get the curre
5 min read
Practice Tags :
three90RightbarBannerImg