In PHP, the __DIR__
magic constant evaluates to the path to the directory containing the file in which that constant appears.
Is there an equivalent feature in Python?
os.path.dirname(__file__)
In Python 3.4 and newer, that's it – you get an absolute path.
In earlier versions of Python, __file__
refers to the file location relative to the cwd at module import time. If you call chdir
, the information will be lost. If this becomes an issue, you can add the following to the root of your module:
import os.path
_dir = os.path.dirname(os.path.abspath(__file__))
But again, if you only target Python 3.4+, this is no longer necessary.