Python Reliable Path to File
Find the actual path to file
Using pathlib
from pathlib import Path
__location__ = Path(__file__).parent.resolve()
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( f.read() )
Playground
Using os
Python os module provides several useful functions too. This is NOT recommended anymore. But if one insists, we can easily make it work.
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__))
)
)
For the same example as above, 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( f.read() )
We can understand how it works by breaking it down.
os.getcwd(): get current working directory. Current working directory is defined as where the python script is executed.➜ Downloads python temp.py os.getcwd: /Users/datumorphism/Downloads ➜ ~ python Downloads/temp.py os.getcwd: /Users/datumorphism__file__: is basically the file name. Suppose we have a python script with namemain.py.print('__file__: ', __file__)will return
__file__: main.py.os.path.abspathretrieves the absolute path of the file.file_absolute_path = os.path.abspath(__file__)os.path.joinjoins the strings into path, intelligently.print('os.path.join("datumorphism", "main.py"): ', os.path.join("datumorphism", "main.py") )will return
os.path.join("datumorphism", "main.py"): datumorphism/main.py.
Playground
til/programming/python/python-reliable-path:L Ma (2018). 'Python Reliable Path to File', Datumorphism, 12 April. Available at: https://datumorphism.leima.is/til/programming/python/python-reliable-path/.