2011-08-04 54 views
2

問題出在這裏 - 我嘗試泡菜,然後取下他的核心。當我使用pickle.load時,Python似乎認爲我正在嘗試加載一個名爲'Pickle'的文件。下面的代碼:在Python中酸洗時發生EOFError

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 

如果有任何其他錯誤,不要擔心,我依然學習,但我無法解決這個問題。

+0

你'hiscores_file.dat'不包含一個完整的Python對象。向我們展示你的酸洗代碼和你在酸洗的東西,也許我們可以看到問題。 – agf

回答

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