The following is an example of how to use the data storage module shelve in Python.

Source: Internet
Author: User

The following is an example of how to use the data storage module shelve in Python.

Shelve is similar to a key-value database and can be easily used to store Python memory objects. It uses pickle internally to serialize data. In short, you can save a list, Dictionary, or custom class instance to shelve. It is a Python memory object, you do not need to retrieve data like a traditional database, and then use the data to reconstruct the required objects. The following is a simple example:

Import shelvedef test_shelve (): # open returns an instance of the Shelf class # parameter flag value range: # 'r': Read-only open # 'W ': read/write access # 'C': read/write access. If it does not exist, create # 'N': read/write access. New and empty database files are always created. # protocol: consistent with the pickle library # writeback: True, when the data changes, it will write back, but it will cause a large memory overhead d = shelve. open ('shelve. db', flag = 'C', protocol = 2, writeback = False) assert isinstance (d, shelve. shelf) # insert a record d ['abc'] = {'name': ['A', 'B']} d in the database. sync () print d ['abc'] # writeback is False, so When lue is modified, d ['abc'] ['X'] = 'X' print d ['abc'] # or print {'name ': ['A', 'B']} # Of Course, directly replace the value of the key. d ['abc'] = 'xxx' print d ['abc'] # restore the content of abc, prepare d ['abc'] = {'name': ['A', 'B']} d for the following test code. when the value of close () # writeback is True, modifications to the field content are writeback to the database. D = shelve. open ('shelve. db', writeback = True) # The content of abc saved above is {'name': ['A', 'B']}, print it out and check whether print d ['abc'] # modifies part of abc's value. d ['abc'] ['xx'] = 'xxx' print d ['abc ''] d. close () # re-open the database and check whether the abc content is correct. writeback d = shelve. open ('shelve. db') print d ['abc'] d. close ()

There is a potential small problem as follows:

>>> import shelve >>> s = shelve.open('test.dat') >>> s['x'] = ['a', 'b', 'c'] >>> s['x'].append('d') >>> s['x'] ['a', 'b', 'c'] 

Where did the stored d go? Actually, it's very simple. d hasn't written back. You saved ['A', 'B', 'C'] to x. When you read s ['X'] Again, s ['X'] is just a copy, but you haven't written the copy back. So when you read s ['X'] Again, it reads a copy from the source, therefore, your new content will not appear in the copy. The solution is to use a cached variable, as shown below:

>>> temp = s['x'] >>> temp.append('d') >>> s['x'] = temp >>> s['x'] ['a', 'b', 'c', 'd'] 

Another method after python2.4 is to assign the value of the writeback parameter of the open Method to True. In this way, all the content after you open the method will be in the cache, when you close, write all the data to the hard disk at one time. If the data volume is not large, we recommend that you do this.

The following is the code for a simple shelve-based database.

#database.py import sys, shelve  def store_person(db):   """   Query user for data and store it in the shelf object   """   pid = raw_input('Enter unique ID number: ')   person = {}   person['name'] = raw_input('Enter name: ')   person['age'] = raw_input('Enter age: ')   person['phone'] = raw_input('Enter phone number: ')   db[pid] = person  def lookup_person(db):   """   Query user for ID and desired field, and fetch the corresponding data from   the shelf object   """   pid = raw_input('Enter ID number: ')   field = raw_input('What would you like to know? (name, age, phone) ')   field = field.strip().lower()   print field.capitalize() + ':', \     db[pid][field]  def print_help():   print 'The available commons are: '   print 'store :Stores information about a person'   print 'lookup :Looks up a person from ID number'   print 'quit  :Save changes and exit'   print '?   :Print this message'  def enter_command():   cmd = raw_input('Enter command (? for help): ')   cmd = cmd.strip().lower()   return cmd  def main():   database = shelve.open('database.dat')   try:      while True:       cmd = enter_command()       if cmd == 'store':         store_person(database)       elif cmd == 'lookup':         lookup_person(database)       elif cmd == '?':         print_help()       elif cmd == 'quit':         return    finally:     database.close() if __name__ == '__main__': main() 

Articles you may be interested in:
  • Anydbm template and shelve template User Guide in Python
  • Python uses the shelve module to implement simple data storage
  • Python implements modifying object instances through shelve
  • Usage of python pickle and shelve modules
  • Example of using the Data Object Persistence storage module pickle in Python
  • Detailed introduction to the python persistent management pickle Module
  • Introduction to Python pickle class library (Object serialization and deserialization)
  • Examples of cPickle usage in python

Related Article

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.