我的代码仅可用于添加和删除一项。但是,添加多个项目时,无法删除其中的任何一个。我认为问题是我的代码将整个字符串(包括空格的所有项目)读取为一个项目。如何在购物车中将它们分开?
file = open('/Users/home/Shopping list.txt', 'w')
file.write("Shopping list\n")
file.close()
print("Welcome to the shopping list creator")
print()
def shoppinglist():
print('''Choose 1 to veiw your shopping list.
Choose 2 to add an item to your shopping list.
Choose 3 to delete an item from your shopping list.
Choose 4 to exit the program.''')
print()
choice = int(input("Enter your choice: "))
if choice == 1:
shoppinglist_file = open('/Users/home/Shopping list.txt')
print()
print(shoppinglist_file.read())
print()
shoppinglist_file.close()
shoppinglist()
elif choice == 2:
shoppinglist_file = open('/Users/home/Shopping list.txt', 'a')
print()
thing_to_add = str(input("What would you like to add to your shopping list? "))
shoppinglist_file.write("%s" % (thing_to_add))
shoppinglist_file.close()
print()
shoppinglist()
elif choice == 3:
shoppinglist_file = open('/Users/home/Shopping list.txt')
shoppinglistfile_list = shoppinglist_file.readlines()
print()
print(shoppinglistfile_list)
del_item = str(input())
print(del_item)
shoppinglistfile_list.remove(del_item)
shoppinglist_file.close()
shoppinglist_file = open('/Users/home/Shopping list.txt', 'w')
shoppinglist_file.write(str(shoppinglistfile_list))
shoppinglist_file.close()
print()
shoppinglist()
elif choice == 4:
print()
print("Thank you for using ths program")
print("--------")
else:
print()
print("Please enter a valid option")
print()
shoppinglist()
shoppinglist()
答案 0 :(得分:0)
您不是要写换行符来表示行尾。
尝试像这样添加model_function
:
\n
答案 1 :(得分:0)
首先,就像提到的MGP一样,您没有添加换行符。您首先需要将其修复为
entityManager.clear()
现在您可以看到运行shoppinglist_file.write("%s\n" % (thing_to_add))
时,print(shoppinglistfile_list)
方法不会修剪任何换行符。例如,如果您的readlines()
如下:
Shopping List.txt
(明确写上换行符以供说明)
那么您的apples\n
oranges\n
bananas\n
将是shoppinglistfile_list
。
['apples\n', 'oranges\n', 'bananas\n']
但是将换行符视为定界符,这意味着您不可能使用它来传递input()
。因此,对于同一示例,输入\n
不会删除apples
。这很容易解决:只需添加apples\n
。
\n
您可能还想更改购物清单的打印方式,因为shoppinglistfile_list.remove(del_item + '\n')
并不是最漂亮的(至少对我而言)。