|
Python Phrasebook(c) Essential Code and Commands Authors: Dayley B. Published year: Pages: 67-68/138 |
Storing Objects in a Shelve File
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 |
Retrieving Objects from a 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 , 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 Authors: Dayley B. Published year: Pages: 67-68/138 |
![]() Python Pocket Reference: Python in Your Pocket (Pocket Reference (O'Reilly)) | ![]() Linux Phrasebook | ![]() Java Phrasebook | ![]() Python Essential Reference (4th Edition) | ![]() The Quick Python Book, Second Edition |
![]() Python Pocket Reference: Python in Your Pocket (Pocket Reference (O'Reilly)) | ![]() Linux Phrasebook |
![]() Java Phrasebook | ![]() Python Essential Reference (4th Edition) |
![]() The Quick Python Book, Second Edition |