I have a text file that contains the XP of the player in it. Every time the game starts:
if os.path.getsize("game_data.txt") != 0: with open("game_data.txt"), "r") as f: XP = f.readline() else: XP = 0
, so that the XP of the player sets to the only item in the file. And at the end of the file (around pygame.quit()
) it has this code:
with open("game_data.txt", "w") as f: f.write(str(XP))
But whenever I try to do XP += (some number)
in my code, I get an error saying that XP
is a string (because what I .read() is always a string) so I cannot use += with a number. Is there a way to explicitly convert what you .read()
to __int__
?
Advertisement
Answer
Try following code
if os.path.getsize("game_data.txt") != 0: with open("game_data.txt"), "r") as f: XP = int(float(f.readline())) else: XP = 0