shelve模块的详细信息见Python库参考:http://docs.python.org/3/library/shelve.html

直接看代码:

 1 # database.py
 2 import sys, shelve
 3 
 4 def store_person(db):
 5     '''
 6     Query user for data and store it in the shelf object
 7     '''
 8     pid = input('Enter unique ID number:')
 9     person = {}
10     person['name'] = input('Enter name:')
11     person['age'] = input('Enter age:')
12     person['phone'] = input('Enter phone:')
13 
14     db[pid] = person
15 
16 def lookup_person(db):
17     '''
18     Query user for ID and desired field, and fetch the corresponding data from the shelf obejct
19     '''
20     pid= input('Enter ID number:')
21     field = input('What would you like to know?(choice option: name,age,phone):')
22     field = field.strip().lower()
23     print(field.capitalize()+':', db[pid][field])
24 
25 def print_help():
26     print('The available commands are:')
27     print('store   :   Stores information about a person')
28     print('lookup  :   Looks up a person from ID number')
29     print('quit    :   Save changes are exit')
30     print('?       :   Prints this message')
31 
32 def enter_command():
33     cmd = input('Enter command(? for help):')
34     cmd = cmd.strip().lower()
35     return cmd
36 
37 def main():
38     database = shelve.open('D:\\database.dat')
39     try:
40         while True:
41             cmd = enter_command()
42             if cmd == 'store':
43                 store_person(database)
44             elif cmd == 'lookup':
45                 lookup_person(database)
46             elif cmd =='?':
47                 print_help()
48             elif cmd == 'quit':
49                 return
50     finally:
51         database.close()
52 
53 if __name__ == '__main__':
54     main()

简单交互过程:

在硬盘上产生的文件:

posted on 2013-04-17 23:02  101010  阅读(264)  评论(0编辑  收藏  举报