標籤:
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 object10 """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] = person17 18 def lookup_person(db):19 """20 Query user for ID and desired field, and fetch the corresponding data from21 the shelf object22 """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 cmd40 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 return54 finally:55 database.close()56 if __name__ == ‘__main__‘: main()
Python中的shelve模組