微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将 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
...

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。