Python Reliable Path to File


Find the actual path to file

Python os module provides several useful functions.

  1. os.getcwd(): get current working directory. Current working directory is defined as where the python script is executed.

    ➜  Downloads python
    os.getcwd:  /Users/datumorphism/Downloads
    ➜  ~ python Downloads/
    os.getcwd:  /Users/datumorphism
  2. __file__: is basically the file name. Suppose we have a python script with name

    print('__file__: ', __file__)

    will return __file__:

  3. os.path.abspath retrieves the absolute path of the file.

    file_absolute_path = os.path.abspath(__file__)
  4. os.path.join joins the strings into path, intelligently.

    print('os.path.join("datumorphism", ""): ', os.path.join("datumorphism", "") )

    will return os.path.join("datumorphism", ""): datumorphism/

The following code will determine the path to the file.

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(os.path.abspath(__file__))))

As an example, we could read a file my_file.json located at the same folder as the python script.

with open(os.path.join(__location__, 'my_file.json'), 'r') as f:
    data_from_file = json.loads( )


Published: by ;

Lei Ma (2018). 'Python Reliable Path to File', Datumorphism, 12 April. Available at:

Current Ref:

  • til/programming/python/