試着這麼做:
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()
。
此外,爲了提高您對該問題的基本理解,您應該檢查出this和this。
更新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。祝你好運!
請在您的問題中包含您的代碼。這將使我們更容易幫助。 – elethan
在所有編程語言中,變量(或列表或字典或其他)都只存在於程序的內存中,並在程序退出時被清除。如果您想保存某些內容,則必須將其放入數據庫或文件或其他外部存儲方法中。 – Cfreak
@Cfreak。保存在當前目錄中的啓動文件也可能工作... –