Storing Objects in a Shelve File


import shelve db = shelve.open("shelved.dat", "n") db['flights'] = flights db['times'] = times print db.keys()

Although pickling is great to store complex Python objects that DBMs cannot, it does not provide the direct entry access that is available with DBMs. Python provides the shelve module to bridge the gap and provide direct access to stored entries, as well as the ability to store complex Python objects. The shelve module accomplishes this by pickling the objects behind the scenes as they are added to the shelve file.

The shelve module provides its own open(filename [, flags [, protocol [, writeback]]]) method to create and open shelve files. The optional flags parameter accepts an r, w, c, or n character to determine whether the shelve will be read, write, created if it doesn't already exist, or truncated to zero length if it does exist. The optional protocol parameter accepts 0, 1, or 2 to determine whether the objects will be pickled as text based, binary, or a newer, faster method, respectively. The writeback parameter, which defaults to false, is a Boolean that, when set to true, causes changes to be cached until the database is closed.

The open method of the shelve module returns a shelve object that behaves much the same as a dictionary. Entries can be added to the shelve by assigning a value to a key using d[key] = value. The key must be a standard string; however, the value can be almost any Python object.

The output from the sample code shows what the contents of the shelve file looks like. You can see the objects in pickled form because the file was created using the default text-based protocol for pickling.

import shelve flights = {"1144":"Dallas", "1045":"Los Angeles", \            "1520":"New York"} times = ["230pm", "320pm", "420pm"] #Create shelve db = shelve.open("shelved.dat", "n") #Store objects in shelve db['flights'] = flights db['times'] = times #Display added keys print db.keys() db.close() #Display the file contents f = open("shelved.dat", "r") data = f.read() print data f.close()


shelve_store.py

['times', 'flights'] |(lp1 S'230pm' p2 aS'320pm' p3 aS'420pm' p4 a.|times|(dp1 S'1520' p2 S'New York' p3 sS'1045' p4 S'Los Angeles' p5 sS'1144' p6 S'Dallas' p7 s.|flights


Output from shelve_store.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