如何向已存在的todos列表添加元素?解决AttributeError报错
解决AttributeError: 'str' object has no attribute 'append'问题
错误原因
你当前代码的核心问题有两个:
file.readline()仅返回文件的第一行字符串,而非列表,所以todos是字符串类型,无法调用列表的append方法。todos变量仅在add分支内定义,show、edit分支直接访问会引发未定义错误。
修复后的代码
# 初始化todos列表,从文件读取现有内容 todos = [] try: with open('pyt.txt', 'r') as file: # readlines()返回所有行的列表,包含换行符 todos = file.readlines() except FileNotFoundError: # 如果文件不存在,保持空列表 pass while True: action = input("请选择操作:add(添加)/ show(查看)/ edit(编辑)/ exit(退出): ") match action: case 'add': todo = input("输入学生姓名: ").strip() + '\n' todos.append(todo) # 写入文件保存 with open('pyt.txt', 'w') as file: file.writelines(todos) print("添加成功") case 'show': if not todos: print("当前没有学生记录") continue for ind, expand in enumerate(todos): index = ind + 1 # 去掉换行符,避免输出空行 print(f"{index} - {expand.strip()}") print(f"班级总人数: {len(todos)}") case 'exit': print("\n\n程序已成功退出\n\n再见!") break case 'edit': if not todos: print("当前没有学生记录可编辑") continue try: num = int(input("输入要编辑的序号: ")) num_n = num - 1 if num_n < 0 or num_n >= len(todos): print("序号无效,请输入正确范围的序号") continue edt = todos[num_n].strip() print(f"当前内容: {edt}") newedt = input(f"输入替换内容(替换{edt}): ").strip() + '\n' todos[num_n] = newedt # 保存到文件 with open('pyt.txt', 'w') as file: file.writelines(todos) print("修改成功") except ValueError: print("请输入有效的数字序号") case _: print("无效操作,请输入add/show/edit/exit")
关键改动说明
- 全局初始化todos:在循环外读取文件内容到
todos列表,确保所有操作分支都能访问,避免未定义错误。 - 正确读取文件内容:用
readlines()获取所有行的列表,同时处理文件不存在的情况(用try-except捕获FileNotFoundError)。 - 使用with语句管理文件:自动处理文件的打开和关闭,避免资源泄漏。
- 修复输入输出细节:
- 处理学生姓名的换行符,避免重复添加或输出空行。
- edit分支中修复input参数错误(原代码用元组作为input参数,改为字符串),增加序号有效性校验,捕获输入非数字的异常。
- show分支增加空列表判断,避免无数据时的无效循环。
- 实时同步文件:每次添加或编辑后,立即将
todos列表写入文件,确保数据持久化。
内容的提问来源于stack exchange,提问作者Hassan Mustafa
相关产品推荐
相关产品推荐

