Python中的EOF错误

2024-10-03 17:28:56 发布

您现在位置: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

前面有一堆代码。

错误是:

^{pr2}$

任何帮助都将不胜感激!


Tags: andthetofromdata错误loadit
1条回答
网友
1楼 · 发布于 2024-10-03 17:28:56

您对同一个文件调用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]
>>> 

相关问题 更多 >