获取当前工作目录外的文件的Python代码

1 投票
2 回答
6577 浏览
提问于 2025-04-18 03:33

我想知道,使用Python代码,我怎么能获取当前工作目录以外的文件。

我现在在 e:\names\test.py 这个目录下工作。

dirpath = os.path.dirname(os.path.realpath(__file__))
dirpath prints e:\names

我想在 e:\images 这个目录中获取文件。

我怎么能从 test.py 文件中获取路径 e:\images\imh.png 呢?

我在 test.py 中硬编码了上面的路径,我该如何在 test.py 文件中设置相对路径呢?

相关问题:

2 个回答

1
import sys
import os

sys.path.insert(1, os.path.split(os.getcwd())[0] + '/directory_name')

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

你可以使用:

os.path.split(os.getcwd())[0] 来获取当前目录的上级目录。

接着,你可以使用:

a=os.path.split(os.getcwd())[0]
os.listdir(a)

来列出上级目录里的内容。

另外,这个方法也可以用:

os.listdir(os.pardir)

撰写回答