【问题标题】:FileNotFoundError: [Errno 2] StuckFileNotFoundError:[Errno 2] 卡住
【发布时间】:2021-02-21 22:11:13
【问题描述】:

谁能告诉我为什么会出现这个错误?文件在文件夹中。

import os

with open("C:\\Users\\42077\\Desktop\\test\\vystup\\!output.txt", "a")as f:
    for root, dirs, files in os.walk("C:\\Users\\42077\\Desktop\\test\\"):
        for path in files:
            if path.endswith(".txt"):
                with open(path, 'r') as file:
                    data = file.readlines()
                    f.write("{0} {1}\n".format(data[2], path))

【问题讨论】:

标签: python python-3.x


【解决方案1】:

filesos.walk() 返回的不是文件路径列表,而是os.walk() 当前正在查找的目录中的文件名称(作为字符串)列表 (root)。

for path in files:
    if path.endswith(".txt"):
        with open(path, 'r') as file:

所以最后这里open() 被赋予了一个类似example.txt 的文件名。 当open() 没有给出绝对路径时,它会从current working directory 查找。这意味着它会尝试在此 python 文件所在的任何位置查找此文件,并立即给出错误。

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 2019-08-06
    • 2019-09-20
    • 2020-11-08
    • 2020-09-15
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多