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

python @

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 and then execute as python you wont see this error.

The reason for this behavior is that when you run Python code directly in the interactive Python shell (often referred to as the Python REPL – Read Eval Print Loop), the special variable __file__ is not available. __file__ holds the path of the currently executing script file when Python runs a script. However, in the interactive shell, there is no script file being executed, so __file__ is not defined.

If you wish to run the code in the Python shell without encountering errors, the following approach will work effectively.

os.path.dirname(os.path.abspath(<span class="hljs-string">"__file__"</span>))


  1. Python articles
  2. Spark Examples
  3. PySpark Blogs
  4. Bigdata Blogs
  5. Spark Interview Questions
  6. Official Page
Author: user

Leave a Reply