Long time no write this series of articles, I more and more like to use Python, it in my work occupies a larger proportion. Say less nonsense and go straight to the subject.
ANYDBM allows us to associate a file on a disk with a "Dict-like" object, manipulating the "Dict-like" object, just like manipulating the Dict object, and finally persisting the "dict-like" data to a file. When manipulating this "Dict-like" object, the type of key and value must be a string. Here's an example of using anydbm:
#coding =utf-8 Import anydbm def createdata (): try: db = Anydbm.open (' Db.dat ', ' C ') # Key and value must be a string # db[' int '] = 1 # db[' float '] = 2.3 db[' string '] = "I like python." db[' key ' = ' value ' finally: db.close () def loaddata (): db = Anydbm.open (' Db.dat ', ' R ') for item in Db.items (): Print Item db.close () if __name__ = = ' __main__ ': createdata () loaddata ()
Anydbm.open (filename[, flag[, mode]), filename is the associated file path, and the optional parameter flag can be: ' R ': Read-only, ' W ': Writable, ' C ': If the data file does not exist, it is created, allowing read and write; ' n ': each call to open () re-creates an empty file. mode is the Unix file pattern, such as 0666 means that all users are allowed to read and write.
The shelve module is an enhanced version of ANYDBM, which supports storing any object in the "Dict-like" object that can be serialized by Pickle, but the key must also be a string. The same example, with shelve to achieve:
Import shelve Def createdata (): try: db = Shelve.open (' Db.dat ', ' C ') # Key and value must be string db[' int '] = 1 db[' float '] = 2.3 db[' string '] = "I like python." db[' key ' = ' value ' finally: db.close () def loaddata (): db = Shelve.open (' Db.dat ', ' R ') for item in Db.items (): Print Item db.close () if __name__ = = ' __main__ ': createdata () loaddata ()