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

Python代码中append方法失效报错及todo文件追加保存需求

问题分析

报错AttributeError: 'str' object has no attribute 'append'的原因很明确:你用file.readline()读取文件时,只会返回一行字符串,而append()是列表的专属方法,字符串当然调用不了。另外代码还有几个隐性问题:

  • 每次操作后未正确关闭文件,容易引发资源泄漏
  • 除add外的show、edit、complete操作,未从文件加载最新待办列表,会导致数据不同步
  • 首次运行时若file.txt不存在,打开'r'模式会直接报错

修复方案

  1. 替换读取方法:把readline()改成readlines(),该方法会返回文件所有行组成的列表,才能正常使用append()添加新待办
  2. 用with语句管理文件:自动处理文件的打开与关闭,避免资源泄漏
  3. 处理文件不存在的情况:读取文件时捕获FileNotFoundError,文件不存在则初始化空列表
  4. 统一加载逻辑:每个操作前都从文件加载最新待办,保证操作的是实时数据

修复后的完整代码

while True:
    user_action = input("type add, show,edit,complete or exit:-\n")
    user_action = user_action.strip()
    
    match user_action:
        case "add":
            todo = input("Enter a todo:-\n") + "\n"
            
            # 加载现有待办,处理文件不存在场景
            try:
                with open('file.txt', 'r') as file:
                    todos = file.readlines()
            except FileNotFoundError:
                todos = []
            
            todos.append(todo)
            
            # 写入更新后的待办列表
            with open('file.txt', 'w') as file:
                file.writelines(todos)

        case "show":
            # 加载最新待办
            try:
                with open('file.txt', 'r') as file:
                    todos = file.readlines()
            except FileNotFoundError:
                todos = []
                
            for index, todo in enumerate(todos):
                # 去掉换行符,避免打印多空行
                todo = todo.strip()
                print(f"{index + 1}-{todo}")

        case "edit":
            try:
                with open('file.txt', 'r') as file:
                    todos = file.readlines()
            except FileNotFoundError:
                print("还没有任何待办项")
                continue
                
            try:
                number = int(input("which number of todos you have to edit:-\n")) - 1
                new_todo = input("Enter your new todo:-\n") + "\n"
                todos[number] = new_todo
                
                with open('file.txt', 'w') as file:
                    file.writelines(todos)
            except IndexError:
                print("输入的待办编号不存在")

        case "complete":
            try:
                with open('file.txt', 'r') as file:
                    todos = file.readlines()
            except FileNotFoundError:
                print("还没有任何待办项")
                continue
                
            try:
                number = int(input("which number you want to complete\n")) - 1
                todos.pop(number)
                
                with open('file.txt', 'w') as file:
                    file.writelines(todos)
            except IndexError:
                print("输入的待办编号不存在")

        case "exit":
            break
print("Bye!")

额外优化说明

  • 新增文件不存在的异常处理,首次运行也不会报错
  • 每个操作都加载最新待办列表,确保数据同步
  • 用with语句自动管理文件,无需手动调用close()
  • 打印待办时去除换行符,避免多余空行
  • 编辑和完成操作增加索引越界处理,避免无效输入导致崩溃

内容的提问来源于stack exchange,提问作者pravinnilee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:27:41