Retrieving Objects from a Shelve File


import shelve db = shelve.open("shelved.dat", "r") for k in db.keys():     obj = db[k] flightDB = db['flights'] flights = flightDB.keys() cities = flightDB.values() times = db['times']

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, which defaults to false, is a Boolean that, when set to true, causes changes to be cached until the database is closed.

Note

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. When you open the shelve file to read objects, you must specify the correct protocol to properly unpickle the objects.


The open method of the shelve module opens a shelve file and returns a shelve object that behaves much the same as a dictionary. Once the shelve object has been created, you can use the shelve object similarly to a dictionary.

The keys() and values() functions retrieve a list of keys or values, respectively. You can also access a specific value by referencing using the corresponding key.

Note

When working with shelve files, the values that are returned can be almost any object type. You will need to keep this in mind when managing shelves that have multiple object types stored in them.


import shelve #Open shelve file db = shelve.open("shelved.dat", "r") #Get the keys from the shelve for k in db.keys():     obj = db[k]     print "%s: %s" % (k, obj) #Use keys to get values flightDB = db['flights'] flights = flightDB.keys() cities = flightDB.values() times = db['times'] print "\nDepartures" print "=============================================" x = 0 for flight in flights:     print ("Flight %s leaves for %s at %s" % \           (flight, cities[x],  times[x]))     x+=1 db.close()


shelve_get.py

times: ['230pm', '320pm', '420pm'] flights: {'1520': 'New York', '1144': 'Dallas',  '1045': 'Los Angeles'} Departures ============================================= Flight 1520 leaves for New York at 230pm Flight 1144 leaves for Dallas at 320pm Flight 1045 leaves for Los Angeles at 420pm


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