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

Save and read data from a file in python?

本问题已经有最佳答案,请猛点这里访问。

我成功地创建了一个游戏,除了我不能保存分数。

我一直在尝试保存我用于指向文本文件的变量,并已对其进行了管理,但希望在程序启动时从中读取该变量。

我保存它的代码如下。

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


我建议你使用泡菜库。进一步阅读:python序列化-为什么选择pickle(pickle的好处)。至于你的问题,

I am struggling because if the file does not
exist, it is trying to read from a non-existant file.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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