Question

I am trying to store a high-score in a txt doc and then read it to show it on screen. But when the score that the player got is higherreturning, I would like to change the high-score in the txt file. I know approximately how to do this but the If statement in my code has a little problem:
It keeps saying False... Here is the code:

score = 10
highscoreFile = open('Highscore.txt', 'r+')
HS = highscoreFile.read() #the HS is, let's say, 3
highscoreFile.close()
print 'Your score is', score
print 'The High-Score is', HS
if score > HS:
    print 'newHS'
    newHS = True
    highscoreFile = open('Highscore.txt', 'w+')
    highscoreFile.write('%s' %(score))
    highscoreFile.close()

NOTE: if I put '<' instead for the If statement, it returns True... please explain.

Was it helpful?

Solution 2

read reads the entire file, by default. And that will be treated as a string in Python. Quoting from the documentation,

If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object.

So, you have to explicitly convert the string to a number, like this

HS = int(highscoreFile.read())

OTHER TIPS

You are comparing int with string. The line

if score > HS:

should be ,

if score > int(HS):
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top