Python中序列化时出现EOFError
这是个问题——我想把他的高分记录保存起来,然后再读取出来。当我使用 pickle.load 的时候,Python 好像认为我在试图加载一个叫做 'Pickle' 的文件。以下是我的代码:
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)
这是保存数据的代码:
def send_hiscores(score):
hiscores_file = open("hiscores_file.dat", "ab")
pickle.dump(score, hiscores_file)
hiscores_file.close()
这是我遇到的错误信息:
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
别担心,如果还有其他错误,我还在学习中,但我就是搞不懂这个问题。
1 个回答
3
当你遍历文件时,你会得到以换行符分隔的行。这并不是获取一系列“腌黄瓜”(pickles,指的是一种数据序列化格式)的方法。出现文件结束错误是因为第一行有一个不完整的“腌黄瓜”。
试试这个:
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