2

这就是问题所在 - 我正在尝试腌制,然后解开他的核心。当我使用 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

如果有任何其他错误,请不要担心,我还在学习,但我无法解决这个问题。

4

1 回答 1

3

当您遍历文件时,您会得到换行符分隔的行。这不是你得到一系列泡菜的方式。由于第一行有部分泡菜,因此引发了文件结尾错误。

尝试这个:

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
于 2011-08-04T19:38:58.607 回答