我正在玩pygame游戏。我希望用户在关闭模块后能够获得相同的分数。但它不起作用:
import pickle
filehandle = True
try:
pickle_file = open("points.mvm", 'r')
except:
filehandle = False
if filehandle:
points = pickle.load(pickle_file)
pickle_file.close()
else:
points = 0
它引发了一个EOFerror。呵呵。 当程序关闭时,我会自动保存点数。没问题。
答案 0 :(得分:0)
这应该有效:
import pickle
points = 0
try:
with open('points.mvm', 'rb') as pickle_file:
points = pickle.load(pickle_file)
except IOError:
pass
print points
points += 1
with open('points.mvm', 'wb') as pickle_file:
pickle.dump(points, pickle_file)
请注意,如果您的目录中仍有points.mvm
文件,则需要将其删除,因为它可能已损坏(即非二进制),并会为您提供EOFError
。