Python使用绝对路径时path.exists为False,使用相对路径为True

3 投票
1 回答
9514 浏览
提问于 2025-04-18 18:08

在UNIX环境中,当我使用文件的绝对路径时,os.path.exists返回的是假(false)。但是当我使用相对路径时,这个检查就通过了。为什么会这样呢?

os.path.exists('/home/my/absolute/long/path/file.txt') = False

但是

os.path.exists('./long/path/file.txt') = True

我查看了绝对路径

os.path.abspath('./long/path/file.txt') = '/home/my/absolute/long/path/file.txt'

我试着查看我在ClearCase vob中的文件,结果找到了:

os.path.exists('/vobs/another/vobfile.txt') = True

1 个回答

2

我想看看运行这段代码的结果:

import os
import os.path

fragment = './long/path/file.txt'
assert os.path.exists(fragment)
assert os.path.exists(os.path.join(os.getcwd(), fragment))

我不相信第一个检查会通过,而第二个会失败。

撰写回答