EOFError用Python腌制

时间:2011-08-04 19:11:59

标签: python pickle 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 个答案:

答案 0 :(得分:3)

当您遍历文件时,您会获得换行符。这不是你如何获得一系列泡菜。引发文件结束错误,因为第一行有部分pickle。

试试这个:

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