Get the directory holding the file that I am currently executing

69 Views Asked by At

I have a file main.py stored in ~/project1/code/.

In main.py, I have changed the working directory to import some other .py files:

import os 
os.chdir('~/project2/code/')

Afterwards, I want to point the working directory to the location where main.py is located. However, since I might run main.py from several directories, I don't want to hard-code the location. How can I retrieve the directory that holds the file that I am currently executing?

When I run the provided solutions from here How do I get the path of the Python script I am running in?, I get the following error:

file_path = os.path.realpath(__file__)
Traceback (most recent call last):

  File "<ipython-input-138-c9fbde97a5bf>", line 1, in <module>
    file_path = os.path.realpath(__file__)

NameError: name '__file__' is not defined
0

There are 0 best solutions below