查找当前目录和文件目录

2998 投票
13 回答
4816109 浏览
提问于 2025-04-16 12:39

我该如何确定:

  1. 当前目录(也就是我在运行Python脚本时所在的地方),还有
  2. 我正在执行的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

当前工作目录: os.getcwd()

还有一个__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()

以下是上面提到的模块、常量和函数的文档链接:

撰写回答