晚上好,
我一直用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
任何帮助将不胜感激!
答案 0 :(得分: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]
>>>