[Python]shelve模块实例一则

最近在看到python的shelve模块,借鉴网上的脚本自己修改写了一个实例。 实例说明 实例中,数据写入到和代码同级的database文件之中。 文件数据不能累加写入,每次写入前都会覆盖前面的数据,也就是说只能保存上一次的数据。
  1. import sysshelve     
  2.      
  3. def store_person(db):      
  4.      pid = raw_input('Enter unique ID number: ')      
  5.      person = {}      
  6.      person['name'] = raw_input('Enter name: ')      
  7.      person['age'] = raw_input('Enter age: ')      
  8.      person['phone'] = raw_input('Enter phone number: ')      
  9.      db[pid] = person      
  10.        
  11. def lookup_person(db):      
  12.      pid = raw_input('Enter unique ID number: ')      
  13.      temp = db[pid]      
  14.      print """ID '%s' info:  
  15.         Name: '%s'    
  16.         age: '%s'    
  17.         phone: '%s'     
  18.         """ % (pid,temp['name'],temp['age'],temp['phone'])             
  19.      
  20. Menu = {'r':store_person, 'c':lookup_person}           
  21.        
  22. def main():      
  23.     ShowMenu = """Enter your choice:   
  24.     (R)egist user info    
  25.     (C)heck user info    
  26.     (Q)uit    
  27.     """     
  28.     while True:      
  29.         while True:      
  30.             try:      
  31.                 choice = raw_input(ShowMenu).strip()[0].lower()      
  32.             except(EOFError,KeyboardInterrupt,IndexError):      
  33.                 choice = 'q'      
  34.             print "\nYou picked:['%s']" % choice      
  35.                   
  36.             if choice not in 'rcq':      
  37.                 print 'invalid option, please try again'      
  38.             else:      
  39.                 break     
  40.         if choice == 'q':      
  41.             break     
  42.         PersonInfo = shelve.open('database')      
  43.         Menu[choice](PersonInfo)           
  44.         PersonInfo.close()      
  45.        
  46. if __name__ == '__main__':       
  47.     main()    

你可能感兴趣的:(python,script)