The __file__ Variable in Python

This tutorial will discuss the __file__ variable in Python.

the __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 __file__ variable.

import os



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. file:

def printHello():
    print("Hello World") file:

import hello as h



Hello World

We used the __file__ special variable to get the path of the user-generated module hello in the code above. First, we created the file that contains the printHello() method, which prints Hello World in the console.

Then, we imported the hello module inside our file and called the h.printHello() method. In the end, we printed the path of the file containing the hello module with the print(h.__file__) method.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.