Changing Objects in a Shelve File


import shelve db = shelve.open("shelved.dat", "w", writeback=1) flights = db['flights'] del flights['1144'] flights['1145'] = "Dallas" db['times'] = newtimes db.sync()

Once the shelve file has been opened, you can use the shelve object similarly to a dictionary. If you want to replace an existing object in the shelve with a new one, assign the new value to the corresponding key using d[key] = value. To remove an object from the database, use del d[key] to reference the object by its specific key.

Changing the value of specific parts of an object is where the power of using shelves rather than DBMs becomes very apparent. First, retrieve the object from the shelve by referencing its key using obj = d[key]. Once the object has been retrieved, values of the object can be modified using standard Python. The changes to the object are written back to the shelve file automatically.

Note

In the example, we open the shelve with writeback set to true, so we use the sync() method of the shelve module to force the changes to be flushed to disk.


import shelve newtimes = ["110pm", "220pm", "300pm", "445pm"] #Open shelve file db = shelve.open("shelved.dat", "w", writeback=1) #Get the keys for k in db.keys():     obj = db[k]     print "%s: %s" % (k, obj) print "\n\n" #Use keys to get values flights = db['flights'] times = db['times'] #Update contents of old object del flights['1144'] flights['1145'] = "Dallas" flights['1709'] = "Orlando" #Replace old object with a new object db['times'] = newtimes #Add a new object db['oldtimes'] = times #Flush data to disk db.sync() for k in db.keys():     obj = db[k]     print "%s: %s" % (k, obj) db.close()


shelve_edit.py

times: ['230pm', '320pm', '420pm'] flights: {'1520': 'New York', '1144': 'Dallas',  '1045': 'Los Angeles'} times: ['110pm', '220pm', '300pm', '445pm'] flights: {'1709': 'Orlando', '1520': 'New York',  '1045': 'Los Angeles', '1145': 'Dallas'} oldtimes: ['230pm', '320pm', '420pm']


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