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.