我正在尝试学习python,并且作为一个项目我开始制作购物清单文本脚本。该脚本应该问你是否要添加/删除一个项目到你的列表。它还具有打印列表的功能。您可以将列表保存为.txt文档,并在需要时继续。Python购物清单文本应用程序,保存问题
我的第一个问题是,当我保存列表项并将它们带回来时,所有不同的列表项已成为一个列表项。所以我可以补充一下,但我无法从列表中删除单数项。
我现在试图从.txt文档拆分列表。我认为这会将列表拆分,但现在每次启动脚本时都会添加额外的符号,然后再次启动它。我可以做出一些小的调整,还是我的想法里程?
#I think the main problem is in the program_start_list_update_from_file defenition
# Shopping list simulator
shoppingList = []
def program_start_list_update_from_file():
global shoppingList
outputname = "shoppinglistfile.txt"
myfile = open(outputname, 'r')
lines = str(myfile.read().split(', '))
shoppingList = [lines]
myfile.close()
def shopping_list_sim():
print("Would you like to add (a) delete (d) or list (l) items in your shopping list?")
print('Press (e) for exit and (s) for list saving')
playerInput = input()
outputname = "shoppinglistfile.txt"
try:
if playerInput == "a":
print("What item would you like to add?")
shoppingList.append(input())
print("Item added")
shopping_list_sim()
elif playerInput == "d":
print("What item would you like to remove?")
print(shoppingList)
shoppingList.remove(input())
print("Item removed")
shopping_list_sim()
elif playerInput == "l":
myfile = open(outputname, 'r')
yourResult = ', '.join(myfile)
print(yourResult)
shopping_list_sim()
elif playerInput == "e":
print("Exiting program")
sys.exit()
elif playerInput == "s":
myfile = open(outputname, 'w')
myfile.write(', '.join(shoppingList))
myfile.close()
shopping_list_sim()
else:
print("Please use the valid key")
shopping_list_sim()
except ValueError:
print("Please put in a valid list item")
shopping_list_sim()
program_start_list_update_from_file()
shopping_list_sim()
你能否提供一些输出示例和已保存列表的示例? – TemporalWolf
是的,加了钥匙,香蕉和胡萝卜。首先保存.txt文件后是[''],键,香蕉,胡萝卜。第二次打开程序并添加鼠标并在此保存之后。结果:[“['']”,'钥匙','香蕉','胡萝卜'],鼠标。第三次添加单词实例并保存。结果:['['[''''',''''','''','''',''''),'mouse'],实例。 @TemporalWolf –