在python中保存并读取文件中的数据?

时间:2017-05-24 01:16:24

标签: python python-3.x

我成功创建了一个游戏,但我无法保存分数。

我一直在尝试将用于点的变量保存到文本文件中,并且已经设置了这个,但是想要一种在程序启动时从中读取它的方法。

我的保存代码如下。

def Save():
    f.open("DO NOT DELETE!", "w+")
    f.write(str(points))
    f.close()

1 个答案:

答案 0 :(得分:0)

我建议您使用pickle库。进一步阅读:Python serialization - Why pickle (Benefits of pickle)。至于你的问题,

  

我正在努力,因为如果文件没有   它存在,它试图从一个不存在的文件中读取。

您可以使用try...except...子句来捕获FileNotFoundError

import pickle as pkl

# to read the highscore:
try:
    with open('saved_scores.pkl', 'rb') as fp:
        highscore = pkl.load(fp) # load the pickle file
except (FileNotFoundError, EOFError): # error catch for if the file is not found or empty
    highscore = 0

# you can view your highscore
    print(highscore, type(highscore)) # thanks to pickle serialization, the type is <int>

# you can modify the highscore
highscore = 10000 # :)

# to save the highscore:
with open('saved_scores.pkl', 'wb') as fp:
    pkl.dump(highscore, fp) # write the pickle file