Writing A Top Score To A Data File
I am trying to create a file that will hold just one number; the highscore to a game I am writing. I have f = open('hisc.txt', 'r+') and f.write(str(topScore)) What I want to k
Solution 1:
Maybe it's my preference, but I am much more used to the idiom in which on initialization, you do
f = open('hisc.txt','r')
# do some exception handling so if the file is empty, hiScore is 0 unless you wanted to start with a default higher than 0
hiScore = int(f.read())
f.close()
And then at the end of the game:
if myScore > hiScore:
f = open('hisc.txt', 'w')
f.write(str(myScore))
f.close()
Solution 2:
Erase the entire file
withopen('hisc.txt', 'w'):
pass
Get the number in the file and make it a variable in the game
withopen('hisc.txt', 'r') as f:
highScore = int(f.readline())
Check if the topScore is higher than the number in the file
ifmyScore>highScore:
and if so, replace it
if myScore > highScore:
withopen('hisc.txt', 'w') as f:
f.write(str(myScore))
Putting it all together:
# UNTESTEDdefUpdateScoreFile(myScore):
'''Write myScore in the record books, but only if I've earned it'''withopen('hisc.txt', 'r') as f:
highScore = int(f.readline())
# RACE CONDITION! What if somebody else, with a higher score than ours# runs UpdateScoreFile() right now?if myScore > highScore:
withopen('hisc.txt', 'w') as f:
f.write(str(myScore))
Solution 3:
f = open('hisc.txt', 'w')
f.write('10') # first score
f.close()
highscore = 25#new highscore# Open to read and try to parse
f = open('hisc.txt', 'r+')
try:
high = int(f.read())
except:
high = 0# do the checkif highscore > high:
high = highscore
f.close()
# open to erase and write again
f = open('hisc.txt', 'w')
f.write(str(high))
f.close()
# testprintopen('hisc.txt').read()
# prints '25'
Post a Comment for "Writing A Top Score To A Data File"