os.path.dirname(__file__) 返回空 [英] os.path.dirname(__file__) returns empty
问题描述
我想获取当前目录的路径,在该目录下执行 .py 文件.
I want to get the path of the current directory under which a .py file is executed.
例如一个简单的文件 D:\test.py
代码:
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__)
奇怪的是输出是:
D:\
test.py
D:\test.py
EMPTY
我期待 getcwd()
和 path.dirname()
的结果相同.
I am expecting the same results from the getcwd()
and path.dirname()
.
给定os.path.abspath = os.path.dirname + os.path.basename
,为什么
os.path.dirname(__file__)
返回空?
推荐答案
因为os.path.abspath = os.path.dirname + os.path.basename
不成立.我们宁愿有
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
dirname()
和 basename()
都只将传递的文件名拆分为组件,而不考虑当前目录.如果您还想考虑当前目录,则必须明确这样做.
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__))
这篇关于os.path.dirname(__file__) 返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!