I’m having trouble understanding __file__. From what I understand, __file__ returns the absolute path from which the module was loaded.
I’m having problem producing this: I have a abc.py with one statement print __file__, running from /d/projects/ python abc.py returns abc.py. running from /d/ returns projects/abc.py. Any reasons why?
__file__is guaranteed to be an absolute path in Python 3.9+.In Python 3.4 (changelog)
In Python 3.9 (changelog):
From the documentation:
From the mailing list thread linked by @kindall in a comment to the question:
For the rest of this, consider
sys.pathnot to include''.So, if you are outside the part of
sys.paththat contains the module, you’ll get an absolute path. If you are inside the part ofsys.paththat contains the module, you’ll get a relative path.If you load a module in the current directory, and the current directory isn’t in
sys.path, you’ll get an absolute path.If you load a module in the current directory, and the current directory is in
sys.path, you’ll get a relative path.