Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and loading objects and using pickle

I´m trying to save and load objects using pickle module.
First I declare my objects:

>>> class Fruits:pass ... >>> banana = Fruits()  >>> banana.color = 'yellow' >>> banana.value = 30 

After that I open a file called 'Fruits.obj'(previously I created a new .txt file and I renamed 'Fruits.obj'):

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

After do this I close my session and I began a new one and I put the next (trying to access to the object that it supposed to be saved):

file = open("Fruits.obj",'r') object_file = pickle.load(file) 

But I have this message:

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() ValueError: read() from the underlying stream did notreturn bytes 

I don´t know what to do because I don´t understand this message. Does anyone know How I can load my object 'banana'? Thank you!

EDIT: As some of you have sugested I put:

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

There were no problem, but the next I put was:

>>> object_file = pickle.load(file) 

And I have error:

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 
like image 926
Peterstone Avatar asked Dec 25 '10 15:12

Peterstone


1 Answers

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 cPickle  In [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 further  In [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} 
like image 63
Jim Brissom Avatar answered Sep 24 '22 15:09

Jim Brissom