The error message nameerror: name ‘__file__’ is not defined raised when you use the file global variable in an interactive shell.
In addition to that, the error occurs when Python cannot find the file variable it raises the name __file__ is not defined error.
The file variable is a built-in variable in Python that represents the name of the current file.
The reason is that the python Shell don’t detect the current file path __file__.
Why does this error “name __file__ is not defined”?
Here are the common reasons why the error occurs in your Python script:
❌ Using the file variable in the wrong context.
❌ Using the file variable in a script that has not been saved.
❌ If you are using the file variable in a script that has been imported into another script.
How to fix “nameerror: name ‘__file__’ is not defined”?
To fix the name file is not defined, you have to create a Python script and run the script with the python main.py command instead.
Here are the different solutions that you can use to resolve the error.
1. Use os.path.abspath
You can use the os.path.abspath method to get the absolute path of the current file.
You can use the following command if you need to access the variable in an interactive shell
import os
result = os.path.abspath(__file__)
print(result)
Output:
C:\Users\pies-pc2\PycharmProjects\pythonProject\main.py
Solution 2: Create a Python script
You can make a file named main.py and after that add the following Python script to your file.
import os
r = os.path.join(os.path.dirname(__file__))
print(r)
Output:
C:\Users\pies-pc2\PycharmProjects\pythonProjectAfter that, you may now run your code with the python main.py command rather than using the interactive shell.
Then in your interactive shell input exit() function.
Finally, you can now run your program in the python main.py command.
If you are using Python 2:
✅ python main.pyIf you are using Python 3:
✅ python3 main.pyIf you are using py alias (Windows):
✅ py main.pySolution 3: Use inspect module
You can also use the inspect module to get the filename of the current file.
For example:
✅ import inspect
current_file = inspect.getfile(inspect.currentframe())
print(current_file)
or
✅ import inspect
current_file = inspect.getfile(lambda: None)
print(current_file)Still, the output is the same.
Output:
C:\Users\pies-pc2\PycharmProjects\pythonProject\main.py
Solution 4: Use os.getcwd() to get current file directory
Alternatively, you can use the os.getcwd to get the current working directory.
✅ import os
cwd = os.getcwd()
print(cwd)Output:
C:\Users\pies-pc2\PycharmProjects\pythonProjectConclusion
The error message nameerror: name ‘__file__’ is not defined raised when you use the __file__ global variable in an interactive shell.
This article already provides solutions that will help you to fix the Python error message.
You could also check out other “nameerror” articles that may help you in the future if you encounter them.
- Nameerror name pd is not defined
- Nameerror: name unicode is not defined
- Nameerror: name os is not defined
Hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊
Function-related NameError
NameError on a function usually means the function was not defined yet, the wrong name was used, or the function is in a different scope.
Common triggers
- Function name typo.
caclulate()instead ofcalculate(). - Called before def. At module level.
- Function in wrong module. Imported from a different module than expected.
- Decorated function shadowed. Decorator returned wrong name.
Diagnostic pattern
# BAD — undefined function
def main():
result = compute_total() # NameError if compute_total not defined
main()
# GOOD — check spelling and scope
def compute_total():
return 42
def main():
result = compute_total()
print(result)
main()
# For decorated functions, make sure functools.wraps is used
from functools import wraps
def my_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
Best practices
- Use editor autocomplete. Prevents most typo NameError.
- Order definitions before calls at module level.
- Use type hints. Editor flags undefined names immediately.
- Use functools.wraps in decorators to preserve the original function name.
Official documentation
Frequently Asked Questions
What is Python NameError and what causes it?
NameError is raised when Python encounters a name (variable, function, class) that hasn’t been defined in the current scope. Most common causes: typo in variable name, using a variable before assigning it, missing import, or referencing a variable that was defined inside a function but accessed outside it.
How do I fix ‘name X is not defined’?
Check three things: (1) Is the name a typo? Compare with the spelling where you defined it. (2) Did you import it? Add ‘from module import X’ or ‘import module’ at the top. (3) Is X defined in a different scope (inside a function, conditional branch, or with-block) that hasn’t executed yet at the point you’re using it? Move the definition before the use.
Why does my variable work in one cell but not another (Jupyter)?
Jupyter kernels keep state between cells. If you defined X in cell 5 and run cell 3 later, X exists. But after Kernel-Restart, only the cells you re-run define their variables. Always run cells top-to-bottom on a fresh kernel before submitting. Use ‘Restart and Run All’ to verify your notebook is reproducible.
What is the difference between NameError and AttributeError?
NameError: the name itself doesn’t exist anywhere in scope (typo, missing import, scope issue). AttributeError: the name exists and points to an object, but that object has no such attribute/method (typo on method name, wrong object type). NameError is about the variable; AttributeError is about what’s inside it.
Where can I find more NameError fixes?
Browse the NameError reference hub for 49+ specific fixes (NumPy, pandas, Jupyter, Python 2 to 3 migration). For Python scope rules see the Python Tutorial hub. For attribute-level errors see AttributeError.
