1 min read

Python Dbm Module

The dbm module provides a generic interface to variants of the DBM database — dbm.gnu or dbm.ndbm. If none of these modules is installed, the slow-but-simple implementation dbm.dumb will be used. It behaves like a dictionary, but keys and values are stored in a file.

Importing the Module

import dbm

Opening a Database

To open a database, use dbm.open(). The flags are 'r' (read), 'w' (write), 'c' (create), 'n' (new/overwrite).

import dbm

# Open database, creating it if necessary
with dbm.open('cache', 'c') as db:
    # ... use the database ...
    pass

Writing Data

Data is stored by assigning a value to a key. Keys and values must be strings or bytes.

import dbm

with dbm.open('cache', 'c') as db:
    db['user'] = 'admin'
    db['www.python.org'] = '127.0.0.1'

Reading Data

You can access data using the key. Note that values are returned as bytes.

import dbm

with dbm.open('cache', 'r') as db:
    print(db.get('user')) # Output: b'admin'

    if 'www.python.org' in db:
        print(db['www.python.org']) # Output: b'127.0.0.1'

Iterating

You can iterate over keys in the database.

import dbm

with dbm.open('cache', 'r') as db:
    for key in db.keys():
        print(key)

programming/python/python