Python 为 os.listdir 返回的文件名引发 FileNotFoundError

问题描述 投票:0回答:3

我试图遍历目录中的文件,如下所示:

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'

所以这里出了什么问题?

python error-handling file-not-found
3个回答
12
投票

是因为

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
块将自动处理它)。


2
投票

os.listdir(directory)
返回 directory 中文件
names
的列表。因此,除非
directory
是您当前的工作目录,否则您需要将这些文件名与实际目录连接起来以获得正确的绝对路径:

for filename in os.listdir(path):
    filepath = os.path.join(path, filename)
    f = open(filepath,'r')
    raw = f.read()
    # ...

2
投票

这是使用

pathlib.Path.iterdir
的替代解决方案,它会生成完整路径,而无需加入路径:

from pathlib import Path

path = Path(r'E:/somedir')

for filename in path.iterdir():
    with filename.open() as f:
        ... # process the file
© www.soinside.com 2019 - 2024. All rights reserved.