我是Python初学者。此待办事项列表不是在新行中添加新的待办事项,而是附加在与上一个待办事项相同的行上。当它被添加为“匹配大小写”时,它工作正常,但由于将其更改为“如果添加”,它会附加在同一行上,如:“1. clean car go getgroceries”而不是“1.clean car 2.go get”杂货”。
from unittest import case
from urllib.response import addbase
while True:
user_action = input("Type add, show, edit, complete or exit : ")
user_action = user_action.strip()
if 'add' in user_action or 'new' in user_action or 'more' 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, item in enumerate(todos):
item = item.strip('\n')
row = f"{index + 1} - {item}"
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()
print('Here are existing todos', todos)
new_todo = input("Enter a new todo: ")
todos[number] = new_todo + '\n'
with open('todos.txt', 'w') as file:
file.writelines(todos)
elif 'complete' in user_action:
number = int(user_action[9:])
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("Invalid input")
print("bye")
我希望代码将 .txt 文件和控制台中的列表输出为枚举行,但现在它在控制台和 .txt 文件中输出文本,并将一行中的所有新待办事项与之前的待办事项合并在一起。
确保添加换行符 ( ) 将其附加到列表时,位于每个待办事项的末尾。这是更正的代码的相关部分:
if 'add' in user_action or 'new' in user_action or 'more' in user_action:
todo = user_action[4:]
with open('todos.txt', 'r') as file:
todos = file.readlines()
todos.append(todo + "\n") # Add the new todo with a newline at the end
with open('todos.txt', 'w') as file:
file.writelines(todos)