Dirname (_ _ file _ _)返回空

我想得到执行. py 文件的工作目录路径。

例如,一个简单的带有代码的文件 D:\test.py:

import os


print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)

奇怪的是,输出结果是:

D:\
test.py
D:\test.py
EMPTY

我期待从 getcwd()path.dirname()的相同结果。

鉴于 os.path.abspath = os.path.dirname + os.path.basename,为什么

os.path.dirname(__file__)

空空如也?

275003 次浏览

因为 os.path.abspath = os.path.dirname + os.path.basename不成立。我们宁愿

os.path.dirname(filename) + os.path.basename(filename) == filename

dirname()basename()都只是将传递的文件名拆分为组件,而没有考虑工作目录。如果你还想考虑工作目录,你必须明确地这样做。

若要获取绝对路径的 dirname,请使用

os.path.dirname(os.path.abspath(__file__))
print(os.path.join(os.path.dirname(__file__)))

你也可以这样使用

import os.path


dirname = os.path.dirname(__file__) or '.'

也可以这样使用:

dirname(dirname(abspath(__file__)))
os.path.split(os.path.realpath(__file__))[0]

返回当前脚本的 abspath; os.path.split (abspath)[0]返回当前目录

我想这是一个没有操作系统模块的直接代码。

__file__.split(__file__.split("/")[-1])[0]

自从 Python 3.4以来,你可以使用 pathlib来获得工作目录:

from pathlib import Path


# get parent directory
curr_dir = Path(__file__).parent


file_path = curr_dir.joinpath('otherfile.txt')