简体   繁体   中英

Python equivalent of PHP's __DIR__ magic constant?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM