Anydbm template and shelve template User Guide in Python, anydbmshelve

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.