2017-01-06 27 views
0

我正在尝试学习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() 
+1

你能否提供一些输出示例和已保存列表的示例? – TemporalWolf

+0

是的,加了钥匙,香蕉和胡萝卜。首先保存.txt文件后是[''],键,香蕉,胡萝卜。第二次打开程序并添加鼠标并在此保存之后。结果:[“['']”,'钥匙','香蕉','胡萝卜'],鼠标。第三次添加单词实例并保存。结果:['['[''''',''''','''','''',''''),'mouse'],实例。 @TemporalWolf –

回答

1

问题的来源是

lines = str(myfile.read().split(', ')) 
shoppingList = [lines] 

你分割文件到列表,使得串出该列表中,然后补充说,单一的字符串到一个列表。

shoppingList = myfile.read().split(', ') 

就足够做你想做的事:split为你创建一个列表。


你应该考虑从递归调用切换到一个循环: 每次递归调用的开销增加了,因为它建立了一个新的stack frame,在这种情况下是完全没有必要的。

他们的方式您目前拥有它,每一个新的提示有新的栈帧:

shopping_list_sim() 
    shopping_list_sim() 
     shopping_list_sim() 
      shopping_list_sim() 
       ... 

如果你在一个循环做到这一点,你不递归构建堆栈。

+0

这解决了它!现在唯一的问题是它输出文本的方式,如果我列出它开头的项目,无键,香蕉。因此,当我想要删除一个项目时,它会添加一个额外的符号,如['','keyless','banana']。你知道如何解决这个问题吗? –

+0

随着你提供的代码,我没有看到通过[repl.it](https://repl.it/FCe6/0) – TemporalWolf

+0

我认为这与repl不保存到.txt文件有关。当将项目作为“预览”列表删除项目时,其打印['','无钥匙','香蕉']的原因是因为我正在打印该列表。通过执行print(','.join(shoppingList))来解决这个问题。问题仍然是它将“,”添加到所有列表的开头。 –