我正在尝试在我正在创建的游戏中保存高分,但每次我执行pickle.dump时,它会覆盖我之前的数据。有什么帮助吗?
答案 0 :(得分:2)
您需要加载现有的pickle'd对象,修改它,然后再次将其转储并进行修改。
答案 1 :(得分:1)
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
答案 2 :(得分:0)
当你腌制时,你一次腌制一个物体,所以你可能需要多次腌制。
>>> 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
要解决此问题,请使用while True和try,但不包括:
>>> highscores = []
>>>
>>> while True:
... try:
... highscores.append(pickle.load(f))
... except EOFError:
... break
...
>>> print highscores
现在剩下的就是获得最大值。您可以使用内置的max()
函数执行此操作:
>>> print max(highscores)