Python 为 os.listdir 返回的文件名提供 FileNotFoundError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28799353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python giving FileNotFoundError for file name returned by os.listdir
提问by Aarushi Mishra
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
But Python was throwing FileNotFoundError
even though the file exists:
但是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'
So what is wrong here?
那么这里有什么问题呢?
采纳答案by Antti Haapala
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.listdir
不返回文件的完整路径,只返回文件名部分;也就是说'foo.txt'
,当打开时会想要,'E:/somedir/foo.txt'
因为当前目录中不存在该文件。
Use os.path.join
to prepend the directory to your filename:
用于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
(Also, you are not closing the file; the with
block will take care of it automatically).
(此外,您没有关闭文件;with
块将自动处理它)。
回答by Lukas Graf
os.listdir(directory)
returns a list of file namesin directory
. So unless directory
is your current working directory, you need to join those file names with the actual directory to get a proper absolute path:
os.listdir(directory)
返回文件列表的名称在directory
。因此,除非directory
是您当前的工作目录,否则您需要将这些文件名与实际目录连接起来以获得正确的绝对路径:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
f = open(filepath,'r')
raw = f.read()
# ...