You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将todos.txt移入files文件夹后,Python调用open函数读写文件触发FileNotFoundError的问题求助

将todos.txt移入files文件夹后,Python调用open函数读写文件触发FileNotFoundError的问题求助

嘿,这个问题我之前也碰到过!核心原因特别简单:你把todos.txt移到了files子文件夹里,但代码里还是在原来的路径找文件,Python当然找不到啦😉

问题到底出在哪?

当你用open('todos.txt', 'r')这种相对路径时,Python会在你运行脚本的当前工作目录里搜索文件。现在你把文件挪到了files子文件夹,原来的路径'todos.txt'就指向了一个不存在的位置,直接触发了FileNotFoundError。从你提供的文件结构截图里也能清楚看到,todos.txt确实在files文件夹里,所以咱们得把路径改对才行。

快速解决方法:修改所有文件路径

只需要把代码里所有用到'todos.txt'的地方,改成'files/todos.txt'(或者更明确的'./files/todos.txt',./用来明确表示当前目录的子文件夹)。要注意,你的代码里有2处用到这个路径:

  1. 开头读取文件的with open(...)语句
  2. 退出程序时写入文件的with open(...)语句

修改后的完整代码

while True:
    user_action = input("Type add, show, edit, complete, or exit: ").strip()

    # 修正:指向files子文件夹里的todos.txt
    with open('files/todos.txt', 'r') as file:
        todos = file.readlines()

    match user_action:
        case 'add':
            todo = input("Enter a todo: ") + "\n"
            todos.append(todo)

        case 'show':
            for index, item in enumerate(todos):
                item = item.title()
                print(f"{index + 1}-{item}", end='')

        case 'edit':
            number = int(input("Number of the todo to edit? ")) - 1
            new_todo = input("Enter new todo to replace: ")
            todos[number] = new_todo + "\n"

        case 'complete':
            number = int(input("Number of the todo to complete? ")) - 1
            if 0 <= number < len(todos):
                completed_todo = todos.pop(number)
                print(f"Todo '{completed_todo.strip()}' has been completed!")
            else:
                print("Invalid todo number!")

        case 'exit':
            # 修正:同样指向files子文件夹里的todos.txt
            with open('files/todos.txt', 'w') as file:
                file.writelines(todos)
            break

        case _:
            print("Invalid action. Please type add, show, edit, complete, or exit.")

额外小提示

如果你以后再碰到路径相关的疑惑,可以在代码开头加几行代码排查当前工作目录:

import os
print("当前工作目录:", os.getcwd())

运行后就能看到Python在哪个文件夹里找文件,以后碰到类似问题都能用这个方法快速定位~

备注:内容来源于stack exchange,提问作者ffhdsuhfu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 15:18:07