__file__ in python

What Does __file__ Mean in Python

__file__ is a special variable in python that can take different values depending on where and how you call it. In this article, we will understand what __file__ means in python.


What Does __file__ Mean in Python

In simple terms, __file__ is the pathname of file from which the module where __file__ is called, was loaded. If you call __file__ from within a .py file, say, foo.py, then __file__ will contain the path of foo.py on your disk. Let us say you create the file foo.py in a text editor.

$ sudo vi /home/data/foo.py

Now add the following lines to it.

#file foo.py

print __file__

Next run foo.py with the following command.

$ sudo python foo.py

You will get the following output.

/home/data/foo.py

You can also use __file__ value to derive other path values. Here are some examples.

A = os.path.join(os.path.dirname(__file__), '..')
# A is parent directory of the directory where .py file which contains the above line resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where .py file which contains the above line resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where .py file which contains the above line resides.

Please note, if you move the file to a different location, the value of __file__ will change to reflect the latest path. It is a system variable that cannot be set by you or changed programmatically.

One of the most important uses of this variable is to get paths that are relative to the file, instead of hardcoding them in your application, so that when the file is moved, your code does not break.

Also, remember that __file__ variable has a value only when it is referred to inside a file. If you run a command containing __file__ in your python’s interactive shell, you will get an error ‘__file__ not defined’.

Also read:

Sed Command to Replace String in File
What is __name__ in Python
How to Find Non-ASCII Characters in MySQL
How to Use Reserved Word in MySQL Colum/Table
How to Show Banned IP Address in Fail2ban

Leave a Reply

Your email address will not be published.