2016-08-12 35 views
-1

我的程序設置,所以我可以添加項目從終端列表,但每當我這樣做例如myFile.append('hello')它保持在那裏,但當我退出終端,並做它再次'hello'被刪除。請幫忙。謝謝!如何添加一個項目到Python中的列表中,並保存它

代碼

elif userInput in command: 
    print("Okay, Initializing new command.\n\n") 
    command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower() 
    if command1 == 'keyword': 
     print('You selected keyword, to exit press enter') 
     command2 = raw_input("Which Keyword would you like to edit? ") 
     if command2 == 'calc': 
      command3 = raw_input("Which Keyword would you like to add? ") 
      calc.append(command3) 
      print(calc) 
+5

請在您的問題中包含您的代碼。這將使我們更容易幫助。 – elethan

+2

在所有編程語言中,變量(或列表或字典或其他)都只存在於程序的內存中,並在程序退出時被清除。如果您想保存某些內容,則必須將其放入數據庫或文件或其他外部存儲方法中。 – Cfreak

+0

@Cfreak。保存在當前目錄中的啓動文件也可能工作... –

回答

3

試着這麼做:

with open(myFile, 'a') as f: 
    f.write('hello') 

您可以追加到一個列表與.append但不是一個文件。相反,您可以使用上面的'a'標記附加到文件myFile,其中myFile是文件路徑。

更新:

基於現有的代碼,你想達到什麼,試試這個:

... 


elif userInput in command: 
    print("Okay, Initializing new command.\n\n") 
    command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower() 
    if command1 == 'keyword': 
     print('You selected keyword, to exit press enter') 
     command2 = raw_input("Which Keyword would you like to edit? ") 
     if command2 == 'calc': 
      command3 = raw_input("Which Keyword would you like to add? ") 
      calc = 'path/to/file' 
      with open(calc, 'a+') as f: 
       f.write(command3 + '\n') 
       f.seek(0) #This brings you back to the start of the file, because appending will bring it to the end 
       print(f.readlines()) 

基本上,你正在寫一個文件,並打印後面的所有的單詞的列表寫入該文件。 'a+'標誌將讓你打開一個文件進行閱讀和寫作。此外,除了用print(f.readlines())打印「列表」之外,您可以將它分配給一個變量,並在後面使用一個實際的Python對象list進行操作,如果這是您想要的:wordlist = f.readlines()

此外,爲了提高您對該問題的基本理解,您應該檢查出thisthis

更新2

如果你需要有一個關鍵字的Python list早些時候在你的代碼,你可以添加:

with open('wordlist.txt', 'a+') as f: #wordlist.txt can be changed to be another file name or a path to a file 
    f.seek(0) #opening with `'a+'` because it will create the file if it does not exist, 
       # and seeking because `'a+'` moves to the end of the file 
    calc = f.readlines() 

這將從wordlist.txt讀單詞的列表,並將它們保存到Python的list調用calc。現在因爲calc是一個實際的Python list對象,所以可以使用calc.append('whatever')。後來在你的代碼,當你想所有關鍵字保存回老大難「名單」(這實際上是隻用換行符('\n'分隔字的文本文件),你可以這樣做:

with open('wordlist.txt', 'w+') as f: 
    for word in calc: 
     f.write(word) 
    f.seek(0) 
    print(f.readlines()) 

這將用calc列表中的所有單詞覆蓋您的單詞表文件,並將所有值打印出來並輸出到控制檯。

如果沒有真正理解您的程序應該如何工作或自己編寫它,這和我所能做的一樣好。嘗試提高對Python文件I/O的理解;它不像某些練習那麼複雜,並且將來可以爲簡單的持久數據提供良好的服務。不要閱讀Codecademy上的Python教程this one,以提高您對Python工作原理的一般理解。我不是說這是一種侮辱;我前一段時間自己做了本教程,它確實幫助我創建了Python基礎知識的良好基礎。它還包括a lesson on file I/O。祝你好運!

+0

並讀回來? –

+2

另外,鑑於OP的問題,我認爲在這個答案對他們有用之前,你必須提供更多的信息。 –

+0

我不會低估這個,因爲它不是「錯誤」,但我不確定它對OP的所有幫助。 OP需要一個非常基本的教程來理解存儲和內存之間的差異。 – Cfreak

相關問題