I want to get the path of the current directory under which a .py file is executed.
我想获取执行.py文件的当前目录的路径。
For example a simple file D:\test.py
with code:
例如一个简单的文件D:\测试。py和代码:
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()
.
我期望从getcwd()和path.dirname()中得到相同的结果。
Given os.path.abspath = os.path.dirname + os.path.basename
, why
os.path。abspath = os.path。目录名+ os.path。basename,为什么
os.path.dirname(__file__)
returns empty?
返回空的吗?
5 个解决方案
#1
199
Because os.path.abspath = os.path.dirname + os.path.basename
does not hold. we rather have
因为os.path。abspath = os.path。目录名+ os.path。:不。我们不是有
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.
dirname()和basename()只将传递的文件名分解为组件,而不考虑当前目录。如果还想考虑当前目录,就必须显式地考虑。
To get the dirname of the absolute path, use
要得到绝对路径的dirname,请使用。
os.path.dirname(os.path.abspath(__file__))
#2
6
can be used also like that:
也可以这样使用:
dirname(dirname(abspath(__file__)))
#3
3
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
你也可以用这种方式
#4
3
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
路径.realpath(__file__)返回当前脚本的abspath;分割(abspath)[0]返回当前目录。
#5
0
import os.path
dirname = os.path.dirname(__file__) or '.'
#1
199
Because os.path.abspath = os.path.dirname + os.path.basename
does not hold. we rather have
因为os.path。abspath = os.path。目录名+ os.path。:不。我们不是有
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.
dirname()和basename()只将传递的文件名分解为组件,而不考虑当前目录。如果还想考虑当前目录,就必须显式地考虑。
To get the dirname of the absolute path, use
要得到绝对路径的dirname,请使用。
os.path.dirname(os.path.abspath(__file__))
#2
6
can be used also like that:
也可以这样使用:
dirname(dirname(abspath(__file__)))
#3
3
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
你也可以用这种方式
#4
3
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
路径.realpath(__file__)返回当前脚本的abspath;分割(abspath)[0]返回当前目录。
#5
0
import os.path
dirname = os.path.dirname(__file__) or '.'