Skip to content
Related Articles

Related Articles

Find path to the given file using Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 14 Jul, 2022

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

Method 1: Find the path to the given file using Path.cwd()

Here, the idea of the Current Working Directory (CWD) holds an important place. Think of the CWD as the folder that the Python is running in. Python assumes that the file starts in the CWD if it is called simply by name, so a name-only reference will only work if the file is in Python’s CWD. The Path.cwd() returns the current directory. 

Python3




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


Output:

C:\Users\int.suraj.gupta

Method 2: Find the path to the given file using 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. In order to obtain the Current Working Directory in Python, use the os.getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

Python3




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


Output:

Get current working directory :  C:\Users\int.suraj.gupta

Method 3: Find the path to the given file using pathlib.Path().absolute()

This function of the Python OS module returns the string containing the absolute path to the current working directory.

Python3




import pathlib
 
# current working directory
print(pathlib.Path().absolute())


Output:

C:\Users\int.suraj.gupta

Method 4: Find the path to the given file using os.path.basename

We can get the file name and the directory name of the running file in the below way. The key thing to understand about __file__ is that the interpreter adjusts it at runtime so that Python knows which file it is dealing with when the script uses several modules. The benefit of calling Path( file__) is that it returns a string containing the path and the file you are currently working on. 

  • You can call __file__ while modifying a file. As a result, if you attempt to call it from the shell interpreter, it will not execute.
  •  __file__ does not function in a Jupyter notebook’s context.

Python3




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


Output:

 

Method 5: Find the path to the given file using os.path.abspath

It may sound complicated, but os.path.abspath() simply means that this method returns the pathname to the path supplied as an argument to this function. The documentation claims that this method produces a normalized absolutized version of the pathname path.

Example 1:

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:

 

Example 2: 

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!