Python FileNotFoundError [错误 2] [重复]

Python FileNotFoundError [Errno 2] [duplicate]

提问人:user22250523 提问时间:7/19/2023 更新时间:7/21/2023 访问量:35

问:

我是 python 编码的新手,需要您的专业知识帮助来解决我的以下问题, 目前,我正在尝试从 txt 文件中读取数据,并在将其移动到列表后进一步处理。

以下是我的代码:


case 'add':
            todo = input("enter a todo")+"\n"
            file = open('data.txt','r')
            todos =file.readlines()
            file.close()
            todos.append(todo)
            file = open('data.txt','w')
            file.writelines(todos)
            file.close()

我收到错误(请注意,我的 main.py 和数据.txt都在同一个文件夹中)

 file = open('data.txt','r')
           ^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
python 读取数据 filenotfounderror

评论

0赞 Karl Knechtel 7/19/2023
“请注意,我的 main.py 和数据.txt都在同一个文件夹中” - 请参阅链接的副本,以了解为什么这不是重要的部分。使用不同的规则来查找文件。
1赞 Matthias 7/19/2023
关于重复:我建议不要使用 .该方法更加灵活,不易出错。os.chdirpathlib

答:

-1赞 Ferhat Aytug 7/19/2023 #1

如果它不在同一文件夹中,则应包括所处位置的完整路径;
data.txt

open("D:\Text\data.txt","w+")