Python任务管理列表:替换match-case为if-else后任务换行异常
问题:添加任务时新任务与旧任务拼接在同一行
问题原因
用readlines()读取任务文件时,每一行内容会保留末尾的换行符\n,但从用户输入中提取的新任务task并不包含换行符。直接将无换行符的task追加到tasks列表后,写入文件时新任务会直接拼接在最后一行任务的末尾,导致没有换行分隔。
修复方案
在追加新任务时,给task添加换行符\n,确保写入文件时每个任务单独占一行。
修改后的代码
while True: user_choice = input("Type add, show, edit, complete or exit: ") user_choice = user_choice.strip() if 'add' in user_choice or 'new' in user_choice: task = user_choice[4:] # 给新任务添加换行符,保证写入时单独占一行 task += '\n' with open('tasks.txt', 'r') as file: tasks = file.readlines() tasks.append(task) with open('tasks.txt', 'w') as file: file.writelines(tasks) elif 'show' in user_choice: with open('tasks.txt', 'r') as file: tasks = file.readlines() for index, item in enumerate(tasks): item = item.strip('\n') row = f"{index+1}-{item}" print(row)
可选优化
如果担心用户输入的任务末尾已有换行符(概率极低),可以先检查再添加:
if not task.endswith('\n'): task += '\n' tasks.append(task)
内容的提问来源于stack exchange,提问作者Arihant
相关产品推荐
相关产品推荐

