Python为os.listdir返回的文件名提供FileNotFoundError
发布于 2021-01-29 15:02:06
我试图遍历这样的目录中的文件:
import os
path = r'E:/somedir'
for filename in os.listdir(path):
f = open(filename, 'r')
... # process the file
但是,FileNotFoundError
即使文件存在,Python仍会抛出:
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'
那么,这里出了什么问题?
关注者
0
被浏览
83
1 个回答
-
这是因为
os.listdir
不返回文件的完整路径,仅返回文件名部分;也就是说'foo.txt'
,当打开时会需要,'E:/somedir/foo.txt'
因为该文件在当前目录中不存在。用于
os.path.join
在目录前添加文件名:path = r'E:/somedir' for filename in os.listdir(path): with open(os.path.join(path, filename)) as f: ... # process the file
(此外,您没有关闭文件;该
with
块将自动处理该文件)。