EOFError whilst pickling in Python
Here's the problem - I'm trying to pickle, and then unpickle hiscores. When I use pickle.load, Python seems to think that I'm trying to load a file c开发者_StackOverflowalled 'Pickle' that I have. Here's the code:
def recieve_hiscores():
hiscores_file = open("hiscores_file.dat", "rb")
for i in hiscores_file:
hiscores = pickle.load(hiscores_file)
hiscores = str(hiscores)
print(hiscores)
Here's the pickling code:
def send_hiscores(score):
hiscores_file = open("hiscores_file.dat", "ab")
pickle.dump(score, hiscores_file)
hiscores_file.close()
And here's the error message:
Traceback (most recent call last):
File "C:\Python31\My Updated Trivia Challenge.py", line 106, in <module>
main()
File "C:\Python31\My Updated Trivia Challenge.py", line 104, in main
recieve_hiscores()
File "C:\Python31\My Updated Trivia Challenge.py", line 56, in recieve_hiscores
hiscores = pickle.load(hiscores_file)
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
EOFError
Don't worry if there's any other mistakes, I'm still learning, but I can't work this out.
When you iterate over the file, you get newline separated lines. This is NOT how you get a series of pickles. The end of file error is raised because the first line has a partial pickle.
Try this:
def recieve_hiscores():
highscores = []
with open("hiscores_file.dat", "rb") as hiscores_file:
try:
while True:
hiscore = pickle.load(hiscores_file)
hiscore = str(hiscore)
print(hiscore)
highscores.append(hiscore)
except EOFError:
pass
return highscores
精彩评论