Forums

'__file__' is not defined

Hi,

I have several web scrapers that run every hour or so and have done fine for years. They all started to throw this error about oh, a week or so ago:

Traceback (most recent call last):
  File "/home/greencracker/part-2s/check-part-2s.py", line 52, in <module>
    curr_path = os.path.dirname(os.path.abspath(__file__))
NameError: name '__file__' is not defined

I'm just trying grab the current directory ...

I get that I could just use absolute path .... but I'm filing this to someone else via Github etc. It's gg have a life beyond PythonAnywhere

Any ideas?

Maybe you can replace it with a alternative like

import os
cwd = os.getcwd()

@acehouse, __file__ is used here to make sure that the location of curr_path is stable no matter where the script was run from. os.getcwd removes that stbility.

@greencraker - how are you running that code? If you run it from a Python shell, then __file__ is not defined unless you import the code as a module.

@glenn - oh hmm ... that question is a little above my pay grade. I'm not sure how to answer.

Say the following code:

-if I run in console, I get the error

-if I run as a scheduled task, I don't get the error

(Addendum, now I don't understand why my scrapers broke since this simple code isn't giving error as scheduled task. I'll have to tinker with those a little.)

import os

curr_path = os.path.dirname(os.path.abspath(__file__))
print (curr_path)


Traceback (most recent call last):
  File "/home/greencracker/sandbox/error_tester.py", line 3, in <module>
    curr_path = os.path.dirname(os.path.abspath(__file__))
NameError: name '__file__' is not defined

Looks like you tripped over a bug in our Save and Run code. We have pushed a fix now so it should be working.

Yasss working now, thanks!

Excellent, thanks for confirming!