Python throwing as NameError: name ‘__file__’ is not defined – Solution

python @ Freshers.in

On Executing  os.path.dirname(os.path.realpath(__file__)) in python interactive shell, you will get the error NameError: name ‘__file__’ is not defined.

This is because the python Shell wont detect the current file path __file__ . If you execute this in a file , means, if the command is written in a myprogram.py and then execute as python myprogram.py you wont see this error.

If you still want to execute in python shell  , the following will do without throwing error.

os.path.dirname(os.path.abspath("__file__"))

 

Author: user

Leave a Reply