0

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
Emil
  • 1,531
  • 3
  • 22
  • 47
  • 2
    Does this answer your question? [How do I get the path of the Python script I am running in?](https://stackoverflow.com/questions/595305/how-do-i-get-the-path-of-the-python-script-i-am-running-in) – mkrieger1 Nov 05 '21 at 11:07
  • No, this raises: `NameError: name '__file__' is not defined` – Emil Nov 05 '21 at 11:09
  • It will be defined when you run the file as a script. Apparently you are executing this code in an interactive ipython session? – mkrieger1 Nov 05 '21 at 11:14
  • I see, thank you. Currently, I am testing it in Spyder indeed. But I will run it from the terminal, so then it should work. Thanks – Emil Nov 05 '21 at 11:16

0 Answers0