“EOFError: Ran out of input” Keep getting this err

2019-05-25 10:31发布

问题:

I am writing a quiz program. I am trying to give the user the opportunity to write and add their own question. I have wrote functions to ask and add questions. I am trying to pickle the list of questions so I can auto load new questions anytime somebody adds one.

This is the code I am using to load the pickled file.

sciIn = open('sciList.txt','rb')
sci = pickle.load(sciIn)
sciIn.close()

I have this code in the function that adds questions.

sciOut = open("sciList.txt",'wb')
sci.append(dicQ)
pickle.dump(sci, sciOut)
sciOut.close()

When I run the code I get EOFError: Ran out of input which points to the loading of the pickle. I am not sure what I am doing wrong. I am using Python 3. Thanks for your help!

full code http://pastebin.com/HEp0KhRA

回答1:

I think you might be doing the pickling right, but maybe working from an empty file at some point… and if you do this on the load, you can get odd EOF errors. Also, if you hand-edited the file in any way (or didn't store the data with pickle), then you can also get EOF Errors on loading.

This works (but note I'm storing questions as a dictionary).

>>> import pickle
>>> sciIn = open('sciList.txt', 'rb') # has 2 pickled dict entries already
>>> sci = pickle.load(sciIn)
>>> sci
{'what is a dog?': 'a dog', 'what kind of parrot is that?': 'a dead parrot'}
>>> sciIn.close()
>>> 
>>> sciOut = open('sciList.txt', 'wb')
>>> sci["what's your favorite colour?"] = "python"  
>>> pickle.dump(sci, sciOut)
>>> sciOut.close()

From your code, it looks like you were pickling a list instead of a dictionary (hence the append to add the new question). The above should work for a list, as well, and you'd just append as you have done in your code. Regardless, if you are trying to read from an object from an empty file with pickle, you'll get an EOF Error -- however, if you start your code from a file that was created by pickling an empty list, you shouldn't get an EOF Error.

>>> import pickle
>>> sciIn = open('sciList2.txt', 'rb') # has a pickled empty list
>>> sci = pickle.load(sciIn)
>>> sci
['what is a dog?', 'what kind of parrot is that?']
>>> sciIn.close()
>>> 
>>> sciOut = open('sciList2.txt', 'wb')
>>> sci.append("what's your favorite color?")
>>> pickle.dump(sci, sciOut)
>>> sciOut.close()