os.path.dirname(__ file__)返回空

问题:os.path.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__)

返回空?

I want to get the path of the current directory under which a .py file is executed.

For example a simple file D:\test.py with code:

import os

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

It is weird that the output is:

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

I am expecting the same results from the getcwd() and path.dirname().

Given os.path.abspath = os.path.dirname + os.path.basename, why

os.path.dirname(__file__)

returns empty?


回答 0

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

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

双方dirname()basename()只拆分通过文件名成组件,而不考虑当前目录。如果您还想考虑当前目录,则必须明确地考虑。

要获取绝对路径的目录名,请使用

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

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

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

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

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

回答 1

也可以这样使用:

dirname(dirname(abspath(__file__)))

can be used also like that:

dirname(dirname(abspath(__file__)))

回答 2

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

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

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

os.path.realpath(__file__)return the abspath of the current script; os.path.split(abspath)[0] return the current dir


回答 3

import os.path

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

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

回答 4

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

您也可以使用这种方式

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

You can also use this way