2015-11-02 67 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