Python 为 os.listdir 返回的文件名提供 FileNotFoundError [英] Python giving FileNotFoundError for file name returned by os.listdir
问题描述
我试图遍历目录中的文件,如下所示:
I was trying to iterate over the files in a directory like this:
import os
path = r'E:/somedir'
for filename in os.listdir(path):
f = open(filename, 'r')
... # process the file
但 Python 抛出 FileNotFoundError
即使文件存在:
But Python was throwing FileNotFoundError
even though the file exists:
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'
,因为当前目录中不存在该文件.
It is because os.listdir
does not return the full path to the file, only the filename part; that is 'foo.txt'
, when open would want 'E:/somedir/foo.txt'
because the file does not exist in the current directory.
使用os.path.join
将目录添加到您的文件名中:
Use os.path.join
to prepend the directory to your filename:
path = r'E:/somedir'
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
... # process the file
(此外,您不会关闭文件;with
块会自动处理它).
(Also, you are not closing the file; the with
block will take care of it automatically).
这篇关于Python 为 os.listdir 返回的文件名提供 FileNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!