os.path.dirname(__file__) 返回空 [英] os.path.dirname(__file__) returns empty

查看:132
本文介绍了os.path.dirname(__file__) 返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取当前目录的路径,在该目录下执行 .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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆