It is possible to read values from a text file, do something with them, and then write values back to a file. The important things to take away are:
- Python's powerful
with open(...)
system is the canonical general-purpose recommendation for reading from and writing to files (aka file-IO)
- Make use of conditional statements (boolean logic) to determine if and how to modify data
If you want to take into account the output from your game (user score in the guesses
variable you named), you'll need to modify your highscores
list variable before writing back to the file. The standard way to write is the same with open()
that you used to read from the file, but specifying write mode "w"
instead of read mode "r"
. As a side note, you used "rt"
for "read text" mode - the default mode of "r"
"read" is "read text" mode. See this post for details.
Some caveats for the end-of-code suggestions below:
- You didn't specify if your list of high scores in the text file was an ordered list of numbers or an unordered list. The suggestion below should work regardless of whether or not it's not an ordered list of numbers, so long as you don't care about the list potentially becoming unordered as new high scores are added.
- With your current terminology, "high scores" are achieved with fewer guesses which is a little confusing, but probably not worth refactoring your code.
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(int(line.strip()))
print(f"Old high scores: {highscores}")
#Compare the values from the list and current one
for i in range(len(highscores)):
if highscores[i] > guesses:
# print(guesses)
# print(highscores[i])
beatenscores += 1
i + 1
else:
beatenscores += 0
print("You have beaten " + str(beatenscores)+ " scores")
maxscores = 10
# If a new high score is achieved, replace one of the worst (highest-value)
# scores on the high score list
if beatenscores > 0:
# Make room if max number of high scores already recorded
if len(highscores) > maxscores:
highscores.pop(highscores.index(max(highscores)))
# Add new high score
highscores.append(guesses)
print(f"New high scores: {highscores}")
# Write high score list to file
with open('Numbergame.txt', 'w') as f:
for score in highscores:
f.write(f"{score}\n")