2017-01-06 32 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))來解決這個問題。問題仍然是它將「,」添加到所有列表的開頭。 –