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

Python向列表追加用户输入时出现AttributeError错误求助

问题解决:待办事项管理代码的AttributeError修复

错误原因

你遇到的AttributeError: 'str' object has no attribute 'append'是因为file.readline()返回的是一个字符串(文件的第一行内容),而不是列表。字符串没有append()方法,所以调用todos.append(todo)会报错。

修复后的完整代码

# 初始化todos列表:读取文件内容,处理空文件情况
try:
    with open('todos.txt', 'r') as file:
        # 读取所有行并去除换行符,得到待办事项列表
        todos = [line.strip() for line in file.readlines()]
except FileNotFoundError:
    # 如果文件不存在,创建空列表
    todos = []

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

    match user_action:
        case 'add':
            todo = input('Enter new todo: ')
            todos.append(todo)
            # 将更新后的列表写入文件,每行一个待办事项
            with open('todos.txt', 'w') as file:
                file.write('\n'.join(todos) + '\n')
        
        case 'show':
            if not todos:
                print("No todos in the list.")
                continue
            for index, item in enumerate(todos):
                row = f"{index + 1}-{item.title()}"
                print(row)
        
        case 'edit':
            if not todos:
                print("No todos to edit.")
                continue
            try:
                number = int(input("Enter the number you want to edit: ")) - 1
                if 0 <= number < len(todos):
                    new_todo = input("Enter new todo: ")
                    todos[number] = new_todo
                    # 写入更新后的列表到文件
                    with open('todos.txt', 'w') as file:
                        file.write('\n'.join(todos) + '\n')
                else:
                    print("Invalid todo number.")
            except ValueError:
                print("Please enter a valid number.")
        
        case 'complete':
            if not todos:
                print("No todos to complete.")
                continue
            try:
                number = int(input("Enter what number from the list want to remove: ")) - 1
                if 0 <= number < len(todos):
                    todos.pop(number)
                    # 写入更新后的列表到文件
                    with open('todos.txt', 'w') as file:
                        file.write('\n'.join(todos) + '\n')
                else:
                    print("Invalid todo number.")
            except ValueError:
                print("Please enter a valid number.")
        
        case 'exit':
            print('Goodbye see you later!')
            break
        
        case _:
            print("Invalid command. Please type add, show, complete, edit or exit.")

关键修复点

  • 初始化todos列表:在脚本开头读取文件内容,将每行转为列表元素,同时处理文件不存在的情况(创建空列表)。
  • 替换readline()为readlines():readlines()读取所有行并返回列表,配合列表推导式去除每行的换行符。
  • 使用with语句管理文件:自动处理文件关闭,避免手动close()的遗漏。
  • 写入文件时处理换行:用'\n'.join(todos)将列表元素拼接为每行一个的字符串,确保文件格式正确。
  • 添加边界检查:处理空列表、无效数字输入等情况,提升代码健壮性。
  • 编辑/完成后写入文件:原代码中编辑和完成操作后未保存到文件,修复后每次修改都会同步到文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:55:22