2016-11-10 101 views
-2

晚報所有,EOF錯誤在Python

我已經做在Python程序,它或多或少存在,但最後的結果是引起EOF錯誤,我很困惑,爲什麼或如何解決它!

myFile =open("positionfile.dat", "rb") #opens and reads the file to allow data to be added 
positionlist = pickle.load(myFile) #takes the data from the file and saves it to positionlist 
individualwordslist = pickle.load(myFile) #takes the data from the file and saves it to individualwordslist 
myFile.close() #closes the file 

帶着一堆代碼在它之前。

的錯誤是:

Traceback (most recent call last): 
File "P:/A453 scenario 1 + task 3.py", line 63, in <module> 
    individualwordslist = pickle.load(myFile) #takes the data from the file and saves it to individualwordslist 
EOFError 

任何幫助,將不勝感激!

+1

你確定這是你的腳本嗎?我看到知道錯誤。在你當前的程序中。 –

+1

我們需要了解數據如何寫入文件。 –

+1

你在抱怨解析文件時出現錯誤。您既不顯示該文件中的內容,也不顯示它是如何創建的。有人會怎麼回答?如果你的課程需要幫助,請與你的老師談談,以確保你沒有作弊。 – jonrsharpe

回答

1

你在同一個文件上打兩次pickle.load()。第一次調用將讀取整個文件,將文件指針留在文件末尾,因此爲EOFError。您需要在第二次調用之前使用file.seek(0)重置文件開頭處的文件指針。

>> import pickle 
>>> wot = range(5) 
>>> with open("pick.bin", "w") as f: 
...  pickle.dump(wot, f) 
... 
>>> f = open("pick.bin", "rb") 
>>> pickle.load(f) 
[0, 1, 2, 3, 4] 
>>> pickle.load(f) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/pickle.py", line 1378, in load 
    return Unpickler(file).load() 
    File "/usr/lib/python2.7/pickle.py", line 858, in load 
    dispatch[key](self) 
    File "/usr/lib/python2.7/pickle.py", line 880, in load_eof 
    raise EOFError 
EOFError 
>>> f.seek(0) 
>>> pickle.load(f) 
[0, 1, 2, 3, 4] 
>>>