我试图迭代目录中的文件,如下所示:
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不返回文件的完整路径,仅返回文件名部分;那是'foo.txt'
,当打开时想要'E:/somedir/foo.txt'
因为当前目录中不存在该文件。
Use 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
块会自动处理它)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)