dbm.open()
This function is used to open a dbm database or create a new database if none exist.
Syntax: dbm.open(file, flag=’r’, mode=0o666)
Parameters: This function take following parameters:
file: name of the file.
flag: mode of permissions. which can be 'r', 'w', 'c', or 'n'.
'r': open the existing database with permission to read only.
'w': open the existing database with permission to read and write.
'c': open the database for read and write, also create a new one if it doesn’t exists.
'n': Always create a new database with permission to both read and write.
mode: The Unix mode of the argument which is an octal form default set to 0o666,
used only when new database is to be created.
Return: The object address of the database file.
Code Example
This is based on the DBM on my Linux system.
# ----- import the dbm package
import dbm
# ----- use the open function to create a new
# ----- database named 'mydb' in 'n' mode.
print()
db = dbm.open('mydb','n')
# ----- which dbm module (dbm.gnu, dbm.ndbm, dbm.dumb)
print(f'whichdb {dbm.whichdb("mydb")}')
print()
# ----- insert key/value pairs
db['name'] = 'Glenn Miller'
db['phone'] = 'PEnnsylvania 6-5000'
db['shortname'] = 'Glenn'
db['year'] = '1940'
# ----- get the value using the get method
print('---- get name')
print(db.get('name'))
print()
# ----- print values using value keys and key iterator
for k in db.keys():
print(db.get(k))
print()
db['name'] = 'louis Armstrong'
##db['name'] = None # error
k = db.firstkey()
while k is not None:
print(db[k])
k = db.nextkey(k)
print()
# ----- delete a key/value pair
del db['phone']
for k in db.keys():
print(db.get(k))
print()
# ----- deleting all of the key/value pairs
for k in db.keys():
del db[k]
db.reorganize()
print(f'db count = {len(db.keys())}')
# ----- close the database
db.close()