我正在研究简单的购物车代码,该代码可以从名为Shopping Cart.txt的文本文件中读取和写入。
我可以写入文件,但不能从其中删除。该代码在删除时不会产生任何错误,但不会同时删除。有人可以指出我正确的方向吗?
代码如下:
file = open('/Users/dsmith/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 view 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/dsmith/Shopping list.txt')
print()
print(shoppinglist_file.read())
print()
shoppinglist_file.close()
shoppinglist()
elif choice == 2:
shoppinglist_file = open('/Users/dsmith/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/dsmith/Shopping list.txt')
shoppinglistfile_list = shoppinglist_file.readlines()
print()
print(shoppinglistfile_list)
del_item = str(input)
print(del_item)
shoppinglistfile_list.remove(del_item)
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)
从文件中删除后,您不保存更改。在
之后添加代码shoppinglistfile_list.remove(del_item)
应该有帮助。
shoppinglist_file.close()
shoppinglist_file = open('/Users/dsmith/Shopping list.txt', 'w')
shoppinglist_file.write(shoppinglistfile_list)
shoppinglist_file.close()
以上代码以写模式重新打开文件,然后将购物清单写回,但删除的单词除外。