python os.path.exists 不起作用

0 投票
1 回答
3312 浏览
提问于 2025-04-17 21:59

我提前道个歉,因为我对Python非常陌生。我写了一个我认为很简单的脚本,用来查找缺失的目录。这个脚本会从一个文件中逐行读取内容(每一行都是一个Unix风格的目录),然后检查这个目录是否存在。如果目录不存在,它就会显示一条消息,并把这个目录写入一个输出文件。

问题是,我在输出文件中发现了一些实际上存在的目录,我不明白这是为什么……

我可以肯定,输出文件中列出的第一个目录是存在的,因为我检查了文件开头的十几个目录。我发现第一个目录确实存在,但我检查的其他目录却不存在。我甚至在Python的交互模式下进行了相同的检查,结果是返回了True,所以我不明白为什么这个目录会被写入输出文件。

有没有什么想法?

import os
f = open('missingdirs.out', 'w')
for line in file('alldirs.txt', 'r'):
     if not os.path.exists(line.strip()):
          print "Could not find the path specified: " + line.strip()
          f.write(line.strip()+'\n')
f.close()

下面是输入文件的示例(这些是绝对路径):

/home/sites/shared/lingui/course/0418-0001_AUT_Can
/home/sites/shared/lingui/course/0418-0001_AUT_Do
/home/sites/shared/lingui/course/0418-0001_AUT_How
/home/sites/shared/lingui/course/0418-0001_AUT_Is-Are
/home/sites/shared/lingui/course/0418-0001_AUT_What
/home/sites/shared/lingui/course/0418-0001_AUT_When
/home/sites/shared/lingui/course/0418-0001_AUT_Where

1 个回答

0

这里有一些简单的故障排除步骤……

with open('alldirs.txt','r') as in_:
    lines = list(map(str.strip,in_.readlines()))
print('\n'.join(lines[:10]))
# maybe your input is not what you think it is

import os
path = r"/home/sites/shared/lingui/course/0418-0001_AUT_Can"
print(os.path.exists(path))
# use a string literal rather than the file read -- does THAT work?

我几乎可以肯定,问题出在你的输入文件格式不正确上。

撰写回答