Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find path to the given file using Python

  • Difficulty Level : Expert
  • Last Updated : 13 Jan, 2021

We can get the location (path) of the running script file .py with __file__. __file__ is useful for reading other files and it gives the current location of the running file. It differs in versions. In Python 3.8 and earlier, __file__ returns the path specified when executing the python (or python3) command. We can get a relative path if a relative path is specified. If we specify an absolute path, an absolute path is returned. But in Python 3.9 and later, __file__ always returns an absolute path, the “os” module provides various utilities. 

os.getcwd(): We can get the absolute path of the current working directory. So depending upon the version used, either a relative path or absolute path is retrieved.

Example 1:

Python3




import os
print('Get current working directory :      ', os.getcwd())
print('Get current file name :    ', __file__)

Output:

Example 2: We can get the file name and the directory name of the running file in the below way.

Python3




import os
  
print('File name :    ', os.path.basename(__file__))
print('Directory Name:     ', os.path.dirname(__file__))

Output:

Way to find File name and directory name

Example 3: To get the absolute path of the running file.

Python3




import os
  
print('Absolute path of file:     '
      os.path.abspath(__file__))
print('Absolute directoryname: '
      os.path.dirname(os.path.abspath(__file__)))

Output:

Absolute way to find file and directory name

Example 4: If we specify an absolute path in os.path.abspath(), it will be returned as it is, so if __file__ is an absolute path, no error will occur even if we set os.path.abspath(__file__)

Python3




import os
pythonfile = 'pathfinding.py'
  
# if the file is present in current directory,
# then no need to specify the whole location
print("Path of the file..", os.path.abspath(pythonfile))
  
for root, dirs, files in os.walk(r'E:\geeksforgeeks\path_of_given_file'):
    for name in files:
        
          # As we need to get the provided python file, 
        # comparing here like this
        if name == pythonfile:  
            print(os.path.abspath(os.path.join(root, name)))

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!