FileNotFoundError: [Errno 2] 卡住

时间:2021-02-21 22:11:13

标签: python python-3.x

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

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))

1 个答案:

答案 0 :(得分:0)

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

root

所以最后这里 for path in files: if path.endswith(".txt"): with open(path, 'r') as file: 被赋予一个文件名,如 open()。 当 example.txt 没有给出绝对路径时,它从 open() 中查找。这意味着它会尝试在此 python 文件所在的任何位置找到此文件,并立即给出错误。

相关问题