20

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?

2 Answers2

31
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
  • 278,196
  • 72
  • 453
  • 469
  • `__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
0
from pathlib import Path

Path(__file__).cwd() 

at the moment I use python 3.10.2 and it works

Pathlib vs OS

The os module represents paths as strings with which you cannot do much. The pathlib module represents paths as special objects with useful methods and attributes.

https://builtin.com/software-engineering-perspectives/python-pathlib

Maj
  • 29
  • 4