提问人:KeiGri 提问时间:2/15/2023 最后编辑:KeiGri 更新时间:2/15/2023 访问量:34
Python - 用户输入不创建新的列表项(而是将字符串添加到最新项的末尾)
Python - User input not creating new list item (instead adds string to end of most recent item)
问:
在这里,我有一些基本的“待办事项”列表程序的代码,它允许用户添加、编辑、显示或删除(完成)项目。键入“add”后,用户可以键入一个字符串,该字符串应被视为输入并添加为新的列表项,但是由于某种原因,将采用第一个输入,创建一个列表项,然后将任何其他输入作为附加文本添加到最新的列表项,而不是创建新的列表项。
todos = []
while True:
# Get user input and strip space characters from it
user_action = input("Type add, show, completed, edit, or exit: \n")
user_action = user_action.strip()
if 'add' in user_action or 'new' in user_action:
todo = user_action[4:]
with open('projectFiles/todos.txt', 'r') as file:
todos = file.readlines()
todos.append(todo)
with open('projectFiles/todos.txt', 'w') as file:
file.writelines(todos)
elif 'show' in user_action:
with open('projectFiles/todos.txt', 'r') as file:
todos = file.readlines()
# new_todos = [item.strip('\n') for item in todos]
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('projectFiles/todos.txt', 'r') as file:
todos = file.readlines()
new_todo = input("Enter new 'to do': ")
todos[number] = new_todo + '\n'
print('Here is how it will look', todos)
with open('projectFiles/todos.txt', 'w') as file:
file.writelines(todos)
elif 'completed' in user_action:
number = int(user_action[9:])
with open('projectFiles/todos.txt', 'r') as file:
todos = file.readlines()
index = number - 1
todo_to_remove = todos[index].strip('\n')
todos.pop(index)
with open('projectFiles/todos.txt', 'w') as file:
file.writelines(todos)
message = f'List item called \'{todo_to_remove}\' was removed from the list'
print(message)
elif 'exit' in user_action:
break
else:
print('Please enter a valid command.')
print('Bye')
例如,使用输入:
add Clean
add Phone call
我希望在键入“show”后,列表将显示为:
1 - 清洁
2 - 电话
相反,它显示为:
1 - CleanPhone 呼叫
我尝试删除将列表读取和写入 .txt 文件的“上下文管理器”,但这似乎没有影响任何事情,我不确定还有什么可能导致问题,因为我之前一直在工作并且不记得更改或删除任何内容。
从本质上讲,我正在寻找一些清晰的信息,说明为什么我的“if 'add' in user_action or 'new' in user_action:”块不能创建多个列表项,以及为什么每个后续输入都会添加到第一个列表项。谢谢。
答: 暂无答案
下一个:从用户处获取数字列表作为输入
评论
input()
.strip()