In some small Python applications, when a relational database is not required, it is convenient to use a persistent dictionary to store name/value pairs. It is very similar to a Python dictionary. The main difference is that the data is read and written on the disk. . Another difference is that dbm keys and values must be of string type.
1. Choose dbm module
Python supports many dbm modules, unfortunately, the files created by each dbm module are not compatible.
The following table lists these modules:
Module Description
dbm Choose the best dbm module
dbm.dumb uses a simple but portable implementation of the dbm library
dbm.gnu uses the GNU dbm library
Generally, unless a dbm library has special advanced functions, use the dbm module.
2. Create a persistent dictionary
import dbm db = dbm.open('Bookmark', 'c') #添加选项 db['MyBlog'] = 'jonathanlife.sinaapp.com' print(db['MyBlog']) #保存,关闭 db.close()
The open function has three ways to open dbm:
Flag usage
C open the file to read and write it, create the file if necessary
W open the file to read and write it, if File does not exist, it will not be created
N opens the file for reading and writing, but a new blank file is always created
It is also possible to pass another optional argument representing the mode, which holds a set of UNIX file permissions will not be discussed in detail here.
3. Access the persistent dictionary
The object returned from the open function is regarded as a dictionary object. The access method for values is as follows:
db[‘key’] = ‘value’ value = db[‘key’] #删除值: del db[‘key’] #遍历所有key: for key in db.keys(): #your code here
Code example:
import dbm #open existing file db = dbm.open('websites', 'w') #add item db['first_data'] = 'Hello world' #verify the previous item remains if db['first_data'] != None: print('the data exists') else: print('Missing item') #iterate over the keys, may be slow for key in db.keys(): print("Key=",key," value=",db[key]) #delete item del db['first_data'] #close and save to disk db.close()