I have a text file that contains the XP of the player in it. Every time the game starts:
JavaScript
x
6
1
if os.path.getsize("game_data.txt") != 0:
2
with open("game_data.txt"), "r") as f:
3
XP = f.readline()
4
else:
5
XP = 0
6
, 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:
JavaScript
1
3
1
with open("game_data.txt", "w") as f:
2
f.write(str(XP))
3
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
JavaScript
1
6
1
if os.path.getsize("game_data.txt") != 0:
2
with open("game_data.txt"), "r") as f:
3
XP = int(float(f.readline()))
4
else:
5
XP = 0
6