I am trying to save high scores with pickle, but how do I add to an already pickled document and then get the max?

StackOverflow https://stackoverflow.com/questions/21420269

  •  04-10-2022
  •  | 
  •  

Question

I am trying to save high scores in a game that I am creating, but each time I do a pickle.dump, it overwrites my previous data. Any help?

Was it helpful?

Solution 3

When you pickle, you pickle one object at a time, so you might have to pickle multiple times.

>>> score = 1
>>> f = open('highscores.p', 'wb')
>>> pickle.dump(score, f)
>>> f.close()
>>> score = 15
>>> f = open('highscores.p', 'wb')
>>> pickle.dump(score, f)
>>> f.close()
>>> f = open('highscores.p', 'rb')
>>> print pickle.load(f)
1
>>> print pickle.load(f)
15
>>> print pickle.load(f)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
EOFError

To fix that, use a while True and a try, except:

>>> highscores = []
>>> 
>>> while True:
...     try:
...         highscores.append(pickle.load(f))
...     except EOFError:
...         break
...
>>> print highscores

Now all that is left is to get the maximum. You can use the built in max() function to do this:

>>> print max(highscores)

OTHER TIPS

You would need to load your existing pickle'd object, modify it, and then dump it again with the modifications.

pickled = pickle.load(open('myscript.p'), 'rb')
#then print the pickled information, and change it as needed.
#then dump the edited version back to the original file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top