首页 文章

在python中保存并读取文件中的数据? [重复]

提问于
浏览
0

这个问题在这里已有答案:

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

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

我的保存代码如下 .

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

1 回答

  • 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
    

相关问题