Python中的shelve模組

來源:互聯網
上載者:User

標籤:

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模組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.