Search notes:

Python: __file__

__file__ evaluates to the filename, inclusive path, that a module was loaded from. (Not all modules are required to have a __file__ attribute, see PEP 420 for more details).
In a script, __file__ is filename as it was used on the command line (relative or absolute).

Simple demonstration

The evaluation of __file__ is demonstrated with the following simple Python script (script.py) and module (XYZ.py) that the script loads:
import XYZ

print('This script is:       ',     __file__)
print('XYZ was imported from:', XYZ.__file__)
Github repository about-Python, path: /dunders/__file__/script.py
print('XYZ is implemented in ', __file__)
Github repository about-Python, path: /dunders/__file__/XYZ.py
When executed like so …
P:\ath\to> py example\script.py
… the following is printed:
XYZ is implemented in  p:\ath\to\example\XYZ.py
This script is:        example\script.py
XYZ was imported from: p:\ath\to\example\XYZ.py

See also

Other dunders

Index