NameError: name '__file__' is not defined
Question:
I am trying to store the path of a script into a variable using:
os.path.abspath(os.path.dirname(__file__))
However, it keeps returning a name '__file__' is not defined
error.
here = os.path.dirname(os.path.abspath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
Answers:
Pretty sure you are running this in a terminal in the interactive Python as it is the only place (I’m aware of) to not have __file__
.
Try it in the actual script. This should work.
I run into this when testing / debugging classes in Spyder (nearly every day). The fix is easy: define the __file__
variable to the name of the py module you are testing.
In the interpreter type:
__file__ = 'modulename.py'
Then run the script again. This method has never caused an issue for me.
I am trying to store the path of a script into a variable using:
os.path.abspath(os.path.dirname(__file__))
However, it keeps returning a name '__file__' is not defined
error.
here = os.path.dirname(os.path.abspath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
Pretty sure you are running this in a terminal in the interactive Python as it is the only place (I’m aware of) to not have __file__
.
Try it in the actual script. This should work.
I run into this when testing / debugging classes in Spyder (nearly every day). The fix is easy: define the __file__
variable to the name of the py module you are testing.
In the interpreter type:
__file__ = 'modulename.py'
Then run the script again. This method has never caused an issue for me.