Home > Net >  Error When Trying To Read Int From Txt File Python
Error When Trying To Read Int From Txt File Python

Time:10-29

Im trying to do a highscore system for my python game using a txt file and writing and reading the highscore from/to it. When i try the code under i get this error message: ValueError: invalid literal for int() with base 10: '\x003'

highscorefileR = open(r"highscore.txt","r ")

score =  int(score)

highscore = highscorefileR.read(3)

for line in highscore:
 
    for i in line:
     
        # Checking for the digit in
        # the string
        if i.isdigit() == True:
            score = int(score)
            highscore.rstrip("\x003")
            highscore.rstrip("\x00")
            highscore.rstrip(" \t\r\n\0")
            highscore = int(highscore)
            if score >= highscore 1:
                score = str(score)
                score.rstrip(' \t\r\n\0')
                highscorefileW = open(r"highscore.txt","w")
                highscore = score
                highscorefileR.write(score)


print(highscore)

CodePudding user response:

If it's a plain text file, you shouldn't need all that complication. Just:

with open(r"highscore.txt","r") as highscorefileR:
    highscore = int(highscorefileR.read())

if score > highscore:
    with open(r"highscore.txt","w") as highscorefileW:
        highscorefileW.write(f'{score}\n')

CodePudding user response:

I just Took Highscore = i instead of all of this: highscore.rstrip("\x003") highscore.rstrip("\x00") highscore.rstrip(" \t\r\n\0") highscore = int(highscore)

Because i looks for the digits in the file

Thanks For all your answers!

  • Related