【问题标题】:Python giving FileNotFoundError for file name returned by os.listdirPython 为 os.listdir 返回的文件名提供 FileNotFoundError
【发布时间】:2015-05-02 04:31:48
【问题描述】:

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

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() 输出中既没有看到1febrenamed 也没有看到75_girls_ill_after_having_breakfast_-_Indian_Express.txt
  • 我将 TestT.py 保存在 E:/ADMTM 中。我现在知道它应该在 E:/ADMTM/Articles/1stfebrenamed(存储 .txt 文件的位置)——如果我想读取没有完整目录路径的文件。

标签: python error-handling file-not-found


【解决方案1】:

这是因为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 块会自动处理它)。

【讨论】:

  • 我建议使用新的pathlib.Path.iterdir 函数而不是os.listdir。使用pathlib 更难犯这种愚蠢的错误。面向对象的文件路径 ftw.
  • @Aran-Fey 那么请写一个新的答案
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2015-05-06
    • 2016-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2018-08-04
    相关资源
    最近更新 更多