将 int 变量保存在文本文件中

问题描述

我想将 int 变量“totalbal”保存到一个文本文件中,这样它就不会在您每次退出时重置该变量。

import pygame,sys,time
from pygame.locals import *

cpsecond = open("clickpersecond.txt","r+")
cps = int(cpsecond.read())
baltotal = open("totalbal.txt","r+")
totalbal = int(baltotal.read())
pygame.init()
    while True: # main game loop
        ...

            if event.type == MOUSEBUTTONDOWN:
                totalbal += cps
                savebal = str(totalbal)
                str(baltotal.write(savebal))
                print("Your current money is",savebal,end="\r")
        
        pygame.display.flip()
        clock.tick(30)

当您点击时,它会将变量“totalbal增加+1,当您点击8次时,它会保存在文本文件中,如012345678,我尝试用以下方法修复它:

int(baltotal.write(savebal))

但是没有成功。

<<< Your current money is 1
<<< Your current money is 2
<<< Your current money is 3
<<< Your current money is 4
<<< Your current money is 5
<<< Your current money is 6
<<< Your current money is 7
<<< Your current money is 8

#The text file output: 012345678

解决方法

如果要改写文件,只要在读写完成后关闭即可。

...
with open("totalbal.txt","r+") as baltotal:
    totalbal = int(baltotal.read())
baltotal.close
...
            if event.type == MOUSEBUTTONDOWN:
                totalbal += cps
                with open("totalbal.txt","w") as baltotal:
                    baltotal.write(str(totalbal))
                baltotal.close
...

为了在您的主进程中清晰起见,最好将文件写入委托给一个函数。你还应该考虑你真正想要写多少次这些信息;大多数情况下,不需要经常记录游戏状态。