Robin Bang!
>>> file['Batman'] = 'Ka-Boom!' # change Batman slot
>>> del file['Robin'] # delete the Robin entry
>>> file.close() # close it after changes
Apart from having to import the interface and open and close the DBM file, Python
programs don’t have to know anything about DBM itself. DBM modules achieve this
integration by overloading the indexing operations and routing them to more primitive
library tools. But you’d never know that from looking at this Python code—DBM files
look like normal Python dictionaries, stored on external files. Changes made to them
are retained indefinitely:
C:\...\PP4E\Dbase> python
>>> import dbm # open DBM file again
>>> file = dbm.open('movie', 'c')
>>> for key in file: print(key.decode(), file[key].decode())
...
Cat-woman Splat!
Batman Ka-Boom!
Joker Wham!
As you can see, this is about as simple as it can be. Table 17-1 lists the most commonly
used DBM file operations. Once such a file is opened, it is processed just as though it
were an in-memory Python dictionary. Items are fetched by indexing the file object by
key and are stored by assigning to a key.
Table 17-1. DBM file operations
Python code Action Description
import dbm Import Get DBM implementation
file=dbm.open('filename', 'c') Open Create or open an existing DBM file for I/O
file['key'] = 'value' Store Create or change the entry for key
value = file['key'] Fetch Load the value for the entry key
count = len(file) Size Return the number of entries stored
index = file.keys() Index Fetch the stored keys list (not a view)
found = 'key' in file Query See if there’s an entry for key
del file['key'] Delete Remove the entry for key
for key in file: Iterate Iterate over stored keys
file.close() Close Manual close, not always needed
DBM Files| 1307