Pickling Objects to a File


import cPickle f = open("pickled.dat", "w") p = cPickle.Pickler(f) p.dump(flights) p.dump(times) f.close()

Pickling data to files is one of the simplest ways to get around the limitation that DBM files have of only allowing simple text string storage. The pickle and cPickle modules included with Python provide a simple-to-use interface to pickle entire objects to a file for persistent storage.

Note

The cPickler object is much faster than the pickler object; however, it will not allow you to subclass the pickler and unpickler objects for advanced handling of data.


The idea of pickling is to take an existing Python object and structure the data in such a way that it can be easily written out to an existing file and read back again.

The first step in pickleing Python objects is to open a file with the write permission. Once the file has been opened, use the Pickler(file) method to create a pickler object. The Pickler method accepts a standard file object as its only parameter and returns the pickler object that is used to write objects to the file.

Once the pickler object has been created, you can use the dump(object) method to write almost any Python object to the file. The dump method pickles the object and writes it to the file. As the output of the sample code illustrates, the pickled object is not a standard Python object.

Note

If the same object is dumped to a pickler object twice, only the first object is saved, even if the object has been modified.


import cPickle flights = {"1144":"Dallas", "1045":"Los Angeles",\            "1520":"New York"} times = ["230pm", "320pm", "420pm"] #Create the pickle file f = open("pickled.dat", "w") #Create the pickler object p = cPickle.Pickler(f) #Pickle data to the file p.dump(flights) p.dump(times) f.close() #Display the file contents f = open("pickled.dat", "r") data = f.read() print data f.close()


pickle_data.py

(dp1 S'1520' p2 S'New York' p3 sS'1045' p4 S'Los Angeles' p5 sS'1144' p6 S'Dallas' p7 s.(lp8 S'230pm' p9 aS'320pm' p10 aS'420pm' p11 a.


Output from pickle_data.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net