1

I would like to save the int variable "totalbal" into a text file, so it doesn't resets the variable everytime you quit.

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)

When you click, it increases the variable "totalbal" by +1, when you click 8 times, it saves in the text file like 012345678, i tried to fix it with:

int(baltotal.write(savebal))

but it didn't worked out.

<<< 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
Zgn
  • 132
  • 7
  • 2
    Does this answer your question? [Python, writing an integer to a '.txt' file](https://stackoverflow.com/questions/16131233/python-writing-an-integer-to-a-txt-file) – skowalak May 19 '21 at 12:42

1 Answers1

3

If you want to rewrite the file, just close after read and write.

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

For clarity in your main process it's probably better to delegate the file write to a function. You should also consider how many times you actually want to write this information; mostly a game state wouldn't need to be recorded that often.

Joffan
  • 1,485
  • 1
  • 13
  • 18