Python Data Persistence – dbm Modules

Python Data Persistence – dbm Modules

6.3 dbm Modules

These modules in Python’s built-in library provide a generic dictionary-like interface to different variants of DBM style databases. These databases use binary encoded string objects as key, as well as value. The dbm. gnu module is an interface to the DBM library version as implemented by the GNU project. On the other hand, dbm.ndbm module provides an interface to UNIX nbdm implementation. Another module, dbm. dumb is also present which is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others.

Example

>>> import dbm
> > > db=dbm.open(1mydbm.db' , 'n' )
>>> db[1 title']=1 Introduction to Python'
>>> db['publisher 1] = 'BPB'
>>> db[1 year'] = '2 019 1
>>> db.close( )

As in the case of shelve database, user-specified database name carries ‘.dir’ postfix. The dbm object’s whichdb( ) function tells which implementation of dbm is available on the current Python installation.

Example

>>> dbm.whichdb('mydbm.db')
'dbm.dumb'

The open() function allows mode these flags: ‘c’ to create a new database with reading/write permission, ‘r’ opens the database in read-only mode, ‘w’ opens an existing database for writing, and ‘n’ flag always create a new empty database with read/write permissions.
The dbm object is a dictionary-like object, just like a shelf object. Hence, all dictionary operations can be performed. The following code opens ‘mydbm.db’ with ‘r’ flag and iterates over the collection of key-value pairs.

Example

> > > db=dbm.open('mydbm.db', 'r')
>>> for k,v in db.items():
print (k,v)
b'title' : b'Introduction to Python'
b'publisher' : b'BPB'
b'year' : b'2019'