Anydbm template and shelve template User Guide in Python, anydbmshelve
I haven't written this series of articles for a long time. I like python more and more, and it accounts for a larger proportion in my work. Go straight to the topic.
Anydbm allows us to associate a file on a disk with a "dict-like" object and operate on this "dict-like" object, just like operating on a dict object, finally, you can save the "dict-like" data to a file. When you operate on this dict-like object, the key and value types must be strings. The following example uses anydbm:
# Coding = UTF-8 import anydbm def CreateData (): try: db = anydbm. open ('db. dat ', 'C ') # The key and value must be strings # 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, the optional parameter flag can be: 'r': Read-only, 'w': read/write, 'C': if the data file does not exist, it is created and can be read and written. 'N': creates an empty file every time open () is called. Mode is the file mode in unix. For example, 0666 indicates that all users are allowed to read and write data.
The shelve module is an enhanced version of anydbm. It supports storing any objects that can be serialized by pickle in the "dict-like" object, but the key must also be a string. In the same example, it is implemented with shelve:
Import shelve def CreateData (): try: db = shelve. open ('db. dat ', 'C ') # The key and value must be the 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 ()