os module provides several useful functions.
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 name
print('__file__: ', __file__)
os.path.joinjoins the strings into path, intelligently.
print('os.path.join("datumorphism", "main.py"): ', os.path.join("datumorphism", "main.py") )
os.path.join("datumorphism", "main.py"): datumorphism/main.py.
The following code will determine the path to the file.
__location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__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( f.read() )