Python待办事项应用添加功能异常:新增项未正确显示
Python待办事项应用添加功能异常修复
问题描述
开发Python待办事项应用时,执行add 内容命令添加新待办项后,使用show命令查看列表,发现新增的待办项并未单独显示,而是与列表最后一项内容拼接在一起。
应用代码
while True: user_action = input("type add, show, edit, remove or exit ") user_action = user_action.strip() if 'add' in user_action: todo = user_action[4:] with open('todos.txt', 'r') as file: todos = file.readlines() todos.append(todo) with open('todos.txt', 'w') as file : file.writelines(todos) elif 'show' in user_action: with open('todos.txt', 'r') as file : todos = file.readlines() for index, items in enumerate(todos): items = items.strip("\n") index = index + 1 row = f"{index}-{items}" print(row) elif 'edit' in user_action: number = int(user_action[5:]) print(number) number = number - 1 with open('todos.txt', 'r') as file: todos = file.readlines() new_todo = input("Type the new todo:") todos[number] = new_todo + "\n" with open('todos.txt', 'w') as file : file.writelines(todos) elif 'remove' in user_action: number = int(user_action[6:]) with open('todos.txt', 'r') as file: todos = file.readlines() index = number - 1 todo_to_remove = todos[index].strip("\n") todos.pop(index) with open('todos.txt', 'w') as file : file.writelines(todos) message = f"todo {todo_to_remove} was removed from the list" print(message) elif 'exit' in user_action: break else: print("Command is not valid ") print("bye!")
实际操作及输出
type add, show, edit, remove or exit add bro type add, show, edit, remove or exit show 1-ab 2-cd 3-hihellohikrrish 4-hi 5- 6-hiibro type add, show, edit, remove or exit add broski type add, show, edit, remove or exit show 1-ab 2-cd 3-hihellohikrrish 4-hi 5- 6-hiibrobroski
期望输出
1-ab 2-cd 3-hihellohikrrish 4-hi 5- 6-hii 7-bro 8-broski
问题原因
使用readlines()读取文件时,每一行内容会保留末尾的换行符\n,但添加新待办项时,直接将用户输入的内容(无换行符)追加到列表中。写入文件时,新内容会直接拼接在最后一行的末尾,而非单独成一行。
修复方案
在添加待办项时,给用户输入的内容加上换行符\n,确保每个待办项在文件中都是单独一行。修改add分支中的代码:
将:
todos.append(todo)
改为:
todos.append(todo + "\n")
修复后验证
执行add bro和add broski后,使用show命令会得到符合预期的输出:新增的bro和broski会作为单独的列表项显示,不会与之前的内容拼接。
内容的提问来源于stack exchange,提问作者Krrish
相关产品推荐
相关产品推荐

