Python 为 os.listdir 返回的文件名提供 FileNotFoundError
Python giving FileNotFoundError for file name returned by os.listdir
我试图遍历目录中的文件,如下所示:
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
没有return文件的完整路径,只有文件名部分;即 '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
块将自动处理它)。
os.listdir(directory)
returns directory
中的文件 名称 的列表。因此,除非 directory
是您当前的工作目录,否则您需要将这些文件名与实际目录连接起来以获得正确的绝对路径:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
f = open(filepath,'r')
raw = f.read()
# ...
我试图遍历目录中的文件,如下所示:
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
没有return文件的完整路径,只有文件名部分;即 '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
块将自动处理它)。
os.listdir(directory)
returns directory
中的文件 名称 的列表。因此,除非 directory
是您当前的工作目录,否则您需要将这些文件名与实际目录连接起来以获得正确的绝对路径:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
f = open(filepath,'r')
raw = f.read()
# ...