Saving and loading objects and using pickle Saving and loading objects and using pickle python python

Saving and loading objects and using pickle


As for your second problem:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python31\lib\pickle.py", line 1365, in load encoding=encoding, errors=errors).load() EOFError

After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:

file.seek(0)

What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.

Finally, cPickle is a faster implementation of the pickle module in C. So:

In [1]: import _pickle as cPickleIn [2]: d = {"a": 1, "b": 2}In [4]: with open(r"someobject.pickle", "wb") as output_file:   ...:     cPickle.dump(d, output_file)   ...:# pickle_file will be closed at this point, preventing your from accessing it any furtherIn [5]: with open(r"someobject.pickle", "rb") as input_file:   ...:     e = cPickle.load(input_file)   ...:In [7]: print e------> print(e){'a': 1, 'b': 2}


The following works for me:

class Fruits: passbanana = Fruits()banana.color = 'yellow'banana.value = 30import picklefilehandler = open("Fruits.obj","wb")pickle.dump(banana,filehandler)filehandler.close()file = open("Fruits.obj",'rb')object_file = pickle.load(file)file.close()print(object_file.color, object_file.value, sep=', ')# yellow, 30


You're forgetting to read it as binary too.

In your write part you have:

open(b"Fruits.obj","wb") # Note the wb part (Write Binary)

In the read part you have:

file = open("Fruits.obj",'r') # Note the r part, there should be a b too

So replace it with:

file = open("Fruits.obj",'rb')

And it will work :)


As for your second error, it is most likely cause by not closing/syncing the file properly.

Try this bit of code to write:

>>> import pickle>>> filehandler = open(b"Fruits.obj","wb")>>> pickle.dump(banana,filehandler)>>> filehandler.close()

And this (unchanged) to read:

>>> import pickle>>> file = open("Fruits.obj",'rb')>>> object_file = pickle.load(file)

A neater version would be using the with statement.

For writing:

>>> import pickle>>> with open('Fruits.obj', 'wb') as fp:>>>     pickle.dump(banana, fp)

For reading:

>>> import pickle>>> with open('Fruits.obj', 'rb') as fp:>>>     banana = pickle.load(fp)