Unpickling Objects from a File


import cPickle f = open("pickled.dat", "r") p = cPickle.Unpickler(f) data = p.load()

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 unpickling is to read pickled objects from an existing pickle file and convert those pickled objects back to standard Python objects.

The first step to unpickle Python objects is to open the pickle file with the read permission. Once the file has been opened, use the UnPickler(file) method to create an unpickler object. The UnPickler method accepts a standard file object as its only parameter and returns the unpickler object that is used to read pickled objects from the file.

Once the unpickler object has been created, you can use the load() method to read a pickled object from the file. The object will be restructured and returned as a standard Python object.

import cPickle #Open the pickle file f = open("pickled.dat", "r") #Create the unpickler object p = cPickle.Unpickler(f) #Unpickle an object from the file data = p.load() print "Flight Dictionary:" print data #Unpickle an object from the file data = p.load() print "\nTime List:" print data f.close()


unpickle_data.py

Flight Dictionary: {'1520': 'New York', '1144': 'Dallas',  '1045': 'Los Angeles'} Time List: ['230pm', '320pm', '420pm']


Output from unpickle_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