shelve中有用的函数就是open(),但是下面编写的数据库函数中调用路径是经常出错,如果直接调用一个从来没有用过的文件却能正常运行,暂时没有找出原因。
调用shelve.open()会返回一个shelf对象用来存储内容,将它当做一个普通的字典来存储数据(字典的键一定要是字符串),在存储完毕之后要调用close()函数,关闭文件。
注意为了正确的使用shelve模块修改存储的对象,必须将临时变量绑定到获得的副本上,并且在修改后重新存储这个副本。或者直接将open()中writeback参数设为True。
下面是利用shelve模块建立的小型数据库
1 #encoding=utf-8 2 __author__ = ‘heng‘ 3 #简单的数据库应用程序 4 5 import sys, shelve 6 7 def store_person(db): 8 """ 9 Query user for data and store it in the shelf object 10 """ 11 pid = raw_input(‘Enter unique ID number: ‘) 12 person = {} 13 person[‘name‘] = raw_input(‘Enter name: ‘) 14 person[‘age‘] = raw_input(‘Enter age: ‘) 15 person[‘phone‘] = raw_input(‘Enter phone number: ‘) 16 db[pid] = person 17 18 def lookup_person(db): 19 """ 20 Query user for ID and desired field, and fetch the corresponding data from 21 the shelf object 22 """ 23 pid = raw_input(‘Enter ID number: ‘) 24 field = raw_input(‘What would you like to know? (name, age, phone) ‘) 25 field = field.strip().lower() 26 print field.capitalize() + ‘:‘, 27 db[pid][field] 28 29 def print_help(): 30 print ‘The available commons are: ‘ 31 print ‘store :Stores information about a person‘ 32 print ‘lookup :Looks up a person from ID number‘ 33 print ‘quit :Save changes and exit‘ 34 print ‘? :Print this message‘ 35 36 def enter_command(): 37 cmd = raw_input(‘Enter command (? for help): ‘) 38 cmd = cmd.strip().lower() 39 return cmd 40 41 def main(): 42 database = shelve.open(‘testdata.dat‘) 43 try: 44 while True: 45 cmd = enter_command() 46 if cmd == ‘store‘: 47 store_person(database) 48 elif cmd == ‘lookup‘: 49 lookup_person(database) 50 elif cmd == ‘?‘: 51 print_help() 52 elif cmd == ‘quit‘: 53 return 54 finally: 55 database.close() 56 if __name__ == ‘__main__‘: main()
时间: 2024-10-16 06:06:15