This tutorial will discuss the
__file__ variable in Python.
__file__ Variable in Python
The double underscore surrounding the name of some variables and methods is also known as a dunder in Python. Any variable or method whose name is surrounded by a dunder is a special variable or method by convention. The
__file__ variable is also a special variable used to get the exact path of any modules imported into our code. The following code snippet below shows us how to get the path of an imported module with the
import os print(os.__file__)
We printed the file’s path containing the
os module with the
__file__ special variable in the code above; this can also be used for user-generated modules. The following code snippets show us how to use the
__file__ variable with user-generated modules.
def printHello(): print("Hello World")
import hello as h h.printHello() print(h.__file__)
Hello World /content/hello.py
We used the
__file__ special variable to get the path of the user-generated module
hello in the code above. First, we created the
hello.py file that contains the
printHello() method, which prints
Hello World in the console.
Then, we imported the
hello module inside our
main.py file and called the
h.printHello() method. In the end, we printed the path of the file containing the
hello module with the