2015-11-02 58 views
0

我已經使用將數據讀入的Python

def Save(): 
    savefile = open('save.txt','w') 
    savefile.write(str(currentLocation)+'\n') 
    savefile.close() 
    print("GAME SAVED!", file=sys.stderr) 

工作正常,但是當我去使用加載它...保存文件

def Load(): 
    savefile = open('save.txt', 'r') 
    for line in savefile: 
     currentLocation.append(currentLocation) 
    savefile.close() 

我得到所謂的錯誤:

AttributeError: 'int' object has no attribute 'append'. 

任何理由你可以想到爲什麼這不起作用?

+2

這意味着'currentLocation'是一個'int' - 而不是'list'。順便說一句,你確定要'currentLocation.append(currentLocation)'(追加列表本身)?你可能想要的東西,如:'currentLocation.append(line)' – alfasin

回答

0

您試圖添加到非列表類型的對象:

currentLocation是不是列表

如果你的文件只包含一條線(與加載數),那麼你就可以讀取文件和剝離的內容來獲得無新線,空間,數量等

def Load(): 
    with open('save.txt', 'r') as loadfile: 
     currentLocation = int(loadfile.read().strip()) 

以上聲明將自動關閉日e嵌套代碼後的文件。

還有int casting將讀取的數字從字符串轉換爲int。

+0

我將如何替換值?我只學會了如何讀入列表,你將如何用整數來做到這一點? – Goonertron

+0

@Goonertron我需要看到更多的代碼。用更多代碼更新您的問題,以便我可以幫助您。 –

+0

currentLocation = 0是獲取更新的變量,當我將它保存到文本文件中時,它顯示數字4,例如哪個是正確的,我只是不知道如何用保存的數字替換當前位置中的0在文本文件中。 – Goonertron