anydbm template and Shelve template usage guide in python

Source: Internet
Author: User
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 ()
  • 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.