在文本文件中保存int变量

2024-10-02 16:23:18 发布

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

我想将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

Tags: importtxtyourisopencurrentpygameint
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:18

如果要重写文件,只需在读写后关闭即可

...
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
...

为了使主进程更清晰,最好将文件写入委托给函数。你也应该考虑你到底想写多少次这个信息;大多数情况下,游戏状态不需要经常记录

相关问题 更多 >