I have here some python 3 code that uses the “pickle” module. It is supposed to store high scores for a game. When I open the program again it instead gives me the default “A : 100…” high scores.
def __init__(self):
self.filename = "highscores.dat"
self.numScores = 5
if not os.path.isfile(self.filename):
self.file = open(self.filename, "wb")
self.scores = [100 for i in range(self.numScores)]
self.names = ["A", "B", "C", "D", "E"]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
else:
file = open(self.filename, "rb")
self.highscores = pickle.load(file)
file.close()
self.file = open(self.filename, "wb")
self.names = [highscore[0] for highscore in self.highscores]
self.scores = [highscore[1] for highscore in self.highscores]
def addScore(self, name, score):
self.scores.append(score) #Add new score
self.scores.sort(reverse = True) #Sort
self.names.insert(self.scores.index(score), name)
self.names = self.names[:self.numScores] # Top 5
self.scores = self.scores[:self.numScores]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
def updateFile(self):
pickle.dump(self.highscores, self.file)
This is only the parts of the code where I believe the problem to reside. I will post more if it is needed. I would be happy to answer your questions. thank you.
You’ll need to re-open the file for writing each time. Currently, you are writing new records each time the score changes, all one after the other, in your file. Your file now contains several pickles but only the first is being read.
Change your code to:
with
addScoreunchanged.The highscore file is now being written from scratch each time the score changes.