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")

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net