How to Fix Resolve the NameError: Global Name __File__ Is Not Defined Error in Python

Vaibhav Vaibhav Feb 02, 2024
How to Fix Resolve the NameError: Global Name __File__ Is Not Defined Error in Python

A dunder is a variable surrounded by double underscores. Python is a special variable meant for unique usage and stores special information.

The __file__ is a dunder in Python. It keeps the path to an imported Python module, and its value can be accessed as follows.

import math
import random
import numpy

print(random.__file__)
print(math.__file__)
print(numpy.__file__)

The Python interpreter raises the following error if this variable is not defined.

NameError: global name __file__ is not defined

This article will learn how to resolve this error in Python.

Resolve NameError: global name __file__ is not defined Error in Python

This error arises when we try to access this variable inside the Python shell. All the code should be shifted to a Python file and executed using the following command from the terminal to fix this error.

python <file>.py <command line paramters>
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Error