i have one file which is highcore.txt and it is empty.
i want if txt file is empty or if any number which is score is greater than any number in txt file , update the txt file , here is my code
def game():
return 115
score = game()
with open("highscore.txt") as f:
highScoreStr = f.read()
if int(highScoreStr)<score or highScoreStr=='':
with open("highscore.txt","w") as f:
f.write(str(score))
it is giving error
if int(highScoreStr)<score or highScoreStr=='': ValueError: invalid literal for int() with base 10: ''
how to fix this error
Advertisement
Answer
I don’t think it is possible to pass an empty string through int()
Since you know it starts as an empty string you’re probably better off writing 2 if statements:
if highScorStr == '':
with open("highscore.txt","w") as f:
f.write(str(score))
if int(highScoreStr)<score:
with open("highscore.txt","w") as f:
f.write(str(score))