Python equivalent of PHP's __DIR__ magic constant?

Question:

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?

Asked By: user212218

||

Answers:

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.

Answered By: phihag
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

Answered By: Maj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.