Python为os.listdi返回的文件名提供FileNotFoundError

2024-09-25 16:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

那这里怎么了?


Tags: 文件pathinimport目录forosopen
2条回答

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

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

这是因为^{}不返回文件的完整路径,只返回文件名部分;也就是'foo.txt',当打开时需要'E:/somedir/foo.txt',因为文件不存在于当前目录中。

使用^{}将目录预先设置为文件名:

path = r'E:/somedir'

for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as f:
        ... # process the file

(另外,您没有关闭文件,with块将自动处理它)。

相关问题 更多 >