查找当前目录和文件目录
我该如何确定:
- 当前目录(也就是我在运行Python脚本时所在的地方),还有
- 我正在执行的Python文件的位置?
13 个回答
362
你可能会觉得这个作为参考很有用:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
384
还有一个__file__
属性,可以帮助你找到正在执行的文件的位置。这个Stack Overflow的帖子解释得很清楚: 我怎么才能获取当前执行文件的路径?
4668
要获取一个Python文件所在目录的完整路径,可以在这个文件里写以下代码:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(注意,如果你已经使用过os.chdir()
来改变当前工作目录,上面的代码就不管用了,因为__file__
这个常量的值是相对于当前工作目录的,而os.chdir()
的调用不会改变这个值。)
要获取当前工作目录,可以使用:
import os
cwd = os.getcwd()
以下是上面提到的模块、常量和函数的文档链接:
os
和os.path
模块。__file__
常量。os.path.realpath(path)
(返回"指定文件名的规范路径,消除路径中遇到的任何符号链接")os.path.dirname(path)
(返回"路径path
的目录名")os.getcwd()
(返回"表示当前工作目录的字符串")os.chdir(path)
("将当前工作目录更改为path
")