【发布时间】:2015-05-02 04:31:48
【问题描述】:
我试图遍历目录中的文件,如下所示:
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'
那么这里出了什么问题?
【问题讨论】:
-
我在您的
os.listdir()输出中既没有看到1febrenamed也没有看到75_girls_ill_after_having_breakfast_-_Indian_Express.txt。 -
我将 TestT.py 保存在 E:/ADMTM 中。我现在知道它应该在 E:/ADMTM/Articles/1stfebrenamed(存储 .txt 文件的位置)——如果我想读取没有完整目录路径的文件。
标签: python error-handling file-not-found