Why can I not replace text in .txt file

  file, python, replace, text

Right now, I am making a simple game and am trying to record a high score and save it between times when the game is open. I have a file, best_score.txt that the high score is retrieved from on open and if score == best throughout the game, I want the current score to be saved in that file. The only text in best_score.txt is the score.

Currently, the file is opened and read from like this:

with open("best_score.txt", "r") as f:
    best = int(f.read())
    old_best = best

The high score(best) is pulled from the file, and I have a second copy of the high score(old_best) saved for later.

During the game, if someone beats their high score, best will be set equal to their score as it goes up.

Once they restart or close the game, if score == best this code runs:

with open("best_score.txt", "w") as f:
    f.write(f.replace(str(old_best), str(best)))

This is intended to search for the original high score at the start of the game(old_best) and replace it with the new high score. Right now, when I run the game and beat the high score, the new one doesn’t get recorded. The text file just becomes empty with no text in it at all, or it remains as the previous high score. What am I doing wrong, or what other method can I do to save the score in a text file?

I know there are similar questions on here and explanations on how to write text on other websites, but I just can’t get mine to work. This is my first "big" project in programming(100+ lines) and this is the only thing that’s really stumping me. Any help would be greatly appreciated.

Source: Python Questions

LEAVE A COMMENT