如何存储整数(例如高分),以便即使程序关闭后也能保存?

2024-03-28 18:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使一个游戏,保存一个高分,即使程序已经停止运行,这样,当我再次运行它,高分仍将保存。你知道吗

  • 由于某些原因,pickle模块不能与我正在使用的Python程序一起工作,因此我不能将其作为解决方案。你知道吗
  • 我曾尝试将整数保存为字符串保存到.txt文件中,但当我尝试回叫它时,它总是只打印出来,我不知道如何在回叫后更改该值。你知道吗

我怎么能这么做? 这就是我所尝试的:

def savehighscore(x):
    with open('highscore.txt','w') as file:
        file.write(str(x))
def play():
    #Game code would go here and output a variable "highscore"
    highscore=10 #Example
    oldhighscore=open('highscore.txt')
    if highscore>int(oldhighscore):
        oldhighscore.close()
        with open('highscore.txt','w') as file:
            file.write(highscore)
savehighscore(5)
play()

它输出一个TypeError,表示“oldhighscore”不能转换为整数。你知道吗


Tags: 程序txt游戏playdefaswith整数