我正试图遍历目录中的文件,如下所示:
import os
path = r'E:/somedir'
for filename in os.listdir(path):
f = open(filename, 'r')
... # process the file
但是Python正在抛出FileNotFoundError
,即使文件存在:
Traceback (most recent call last):
File "E:/ADMTM/TestT.py", line 6, in <module>
f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'
那这里怎么了?
^{} 返回
directory
中的文件名列表。因此,除非directory
是您当前的工作目录,否则您需要将这些文件名与实际目录连接起来,以获得正确的绝对路径:这是因为^{} 不返回文件的完整路径,只返回文件名部分;也就是
'foo.txt'
,当打开时需要'E:/somedir/foo.txt'
,因为文件不存在于当前目录中。使用^{} 将目录预先设置为文件名:
(另外,您没有关闭文件,
with
块将自动处理它)。相关问题 更多 >
编程相关推荐