When I try and open/edit a .txt file in python, it deletes whatever is inside of the file. What is doing this?

Viewed 57

Very short and simple. I am trying to create a highscore txt document for one of the games I'm making apart of a project. I want it to be able to keep the highest score ever reached in a text document so I can display it on the screen.

The file already exists, but whenever I load up the game, I get a "invalid literal for int() with base 10:" error. After looking, I realised this was because the file would delete anything inside of it when the program is started. Why is this? How can I fix it?

My code:

hisc = open("snakeScore.txt","w+")
highscore = hisc.read()
highscore_in_no = int(highscore)
if score>highscore_in_no:
            hisc.replace(str(score))
            highscore_in_no = score
2 Answers

Thats becuase You are using "w" when openning the file.

"w" Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

try using "r+" or "a"

From the documentation of Python3 for open:

  • r open for reading (default)
  • w open for writing, truncating the file first
  • '+' open for updating (reading and writing)

Then w+ will truncate the file before writing to it. You don't want that if you are required to read and store the content of it first.

Here's a working code, assuming that snakeScore.txt's content is a single line containing an integer, say "10":

score = 101
with open("snakeScore.txt", 'r+') as f:
    highestscore = int(f.read())
    if score > highestscore:
        f.seek(0)
        f.writelines(str(score))

The call to seek is needed in order to reset the pointer to the first line of the file, so we can rewrite the current line as opposed to adding a new one.

Related