在Python中处理路径

1 投票
3 回答
2801 浏览
提问于 2025-04-16 21:19

我正在Windows上写一个Python 2.5的脚本,当前目录是 CurrentDir = C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\source,我的文件名是 test.py。我想从这个路径访问另一个路径下的文件: C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\Common\

我尝试使用 os.path.join,但没有成功。从文档中我明白了原因。那么,最好的Python解决方案是什么呢?

currentdir = os.getcwd()    
config_file_path =  os.path.join(currentdir,"\\..\\Common")

3 个回答

0

试试这个:

joined = os.path.join('C:\\users\\spring\\projects\\sw\\demo\\753\\ver1.1\\011\\rev120\\source', '..\\Common\\')
# 'C:\\users\\spring\\projects\\sw\\demo\\753\\ver1.1\\011\\rev120\\source\\..\\Common\\'
canonical = os.path.realpath(joined)
# 'C:\\users\\spring\\projects\\sw\\demo\\753\\ver1.1\\011\\rev120\\Common'
2
from os.path import dirname, join
join(dirname(dirname(__file__)), 'Common')

应该可以正常工作。

2

你的问题可以通过使用 os.path.join 来解决,但你没有正确使用它。

currentdir = os.getcwd()    
config_file_path =  os.path.join(currentdir,"\\..\\Common")

"\\..\\Common" 不是一个相对路径,因为它是以 \ 开头的。

你需要使用 ..\\Common,这是一个相对路径。

请注意,os.path.join 不是简单的字符串拼接函数,你不需要在中间插入反斜杠。

所以修正后的代码应该是:

config_file_path =  os.path.join(currentdir,"..\\Common")

或者,另外一种写法是:

config_file_path =  os.path.join(currentdir, "..", "Common")

撰写回答