19

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?

1 Answers1

30
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.

phihag
  • 263,143
  • 67
  • 432
  • 458
  • `__file__` is absolute since 3.4 per https://stackoverflow.com/a/22866630/4200039, and chdir also doesn't seem to be an issue any longer as demonstrated by https://stackoverflow.com/a/23616783/4200039 – Ben Creasy Feb 26 '19 at 07:50
  • 1
    One may wonder "Why the hack they didn't just create a `__dir__` ?" ... it's because of a naming issue - python already used `dir` and `__dir__()` **but for object attribute getting ...** (don't ask me why) still I personally think they could have made up something like `__directory__` #shrug – jave.web Dec 04 '20 at 22:31