The shelve Module

The shelve module, shown in Example 10-3, uses the database handlers to implement persistent dictionaries. A shelve object uses string keys, but the value can be of any datatype, as long as it can be handled by the pickle module.

Example 10-3. Using the shelve Module

File: shelve-example-1.py

import shelve

db = shelve.open("database", "c")
db["one"] = 1
db["two"] = 2
db["three"] = 3
db.close()

db = shelve.open("database", "r")
for key in db.keys():
    print repr(key), repr(db[key])

'one' 1
'three' 3
'two' 2

Example 10-4 shows how to use the shelve module with a given database driver.

Example 10-4. Using the shelve Module with a Given Database

File: shelve-example-3.py

import shelve
import gdbm

def gdbm_shelve(filename, flag="c"):
    return shelve.Shelf(gdbm.open(filename, flag))

db = gdbm_shelve("dbfile")

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.