Python's method of using shelve module to implement simple data storage

Source: Internet
Author: User
Tags unique id

This article illustrates how Python uses the shelve module to implement simple data storage. Share to everyone for your reference. The specific analysis is as follows:

Python's shelve module provides a simple data storage scheme to manipulate data in the form of a dict (dictionary).

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 This is the #!/usr/bin/python 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 F or ID and desired field, and fetch the corresponding data from the shelf object "" "pid = Raw_input (' Enter unique ID Numbe R: ') temp = db[pid] field = raw_input (' Please enter name, age or Phone: ') Field.strip (). Lower () print field.capitalize () + ': ', Temp[field] def print_help (): print ' The avaliable commands are: ' print ' store:stores infomation about a person ' p Rint ' Lookup: Looks up a person form ID number ' print ' Quit:save changes and exit ' print '? :P rints This message ' Def enter_command (): cmd = raw_input (' Enter command (? to help): ' "cmd = Cmd.strip (). Lower () return cmd def main (): Database = Shelve.open (' database ') # database stores in current directory try:while True:cmd = enter_com Mand () if cmd = = ' Store ': Store_person (database) elif cmd = = ' Lookup ': Lookup_person (database) elif cmd = = '? ': Print_help () elif cmd = = ' quit ': Return Finally:database.close () # Close to any condition if __name__ = ' __main__ ': Main ( )

I hope this article will help you with your Python programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.