国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

舉例簡單講解Python中的數據存儲模塊shelve的用法

2020-01-04 17:39:55
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了舉例簡單講解Python中的數據存儲模塊shelve的用法,shelveshelve模塊與pickle模塊的功能相近,比pickle用起來更為簡單,需要的朋友可以參考下
 

shelve類似于一個key-value數據庫,可以很方便的用來保存Python的內存對象,其內部使用pickle來序列化數據,簡單來說,使用者可以將一個列表、字典、或者用戶自定義的類實例保存到shelve中,下次需要用的時候直接取出來,就是一個Python內存對象,不需要像傳統數據庫一樣,先取出數據,然后用這些數據重新構造一遍所需要的對象。下面是簡單示例:

import shelvedef test_shelve():  # open 返回一個Shelf類的實例  #  # 參數flag的取值范圍:  # 'r':只讀打開  # 'w':讀寫訪問  # 'c':讀寫訪問,如果不存在則創建  # 'n':讀寫訪問,總是創建新的、空的數據庫文件  #  # protocol:與pickle庫一致  # writeback:為True時,當數據發生變化會回寫,不過會導致內存開銷比較大  d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False)  assert isinstance(d, shelve.Shelf)  # 在數據庫中插入一條記錄  d['abc'] = {'name': ['a', 'b']}  d.sync()  print d['abc']  # writeback是False,因此對value進行修改是不起作用的  d['abc']['x'] = 'x'  print d['abc'] # 還是打印 {'name': ['a', 'b']}  # 當然,直接替換key的value還是起作用的  d['abc'] = 'xxx'  print d['abc']  # 還原abc的內容,為下面的測試代碼做準備  d['abc'] = {'name': ['a', 'b']}  d.close()  # writeback 為 True 時,對字段內容的修改會writeback到數據庫中。  d = shelve.open('shelve.db', writeback=True)  # 上面我們已經保存了abc的內容為{'name': ['a', 'b']},打印一下看看對不對  print d['abc']  # 修改abc的value的部分內容  d['abc']['xx'] = 'xxx'  print d['abc']  d.close()  # 重新打開數據庫,看看abc的內容是否正確writeback  d = shelve.open('shelve.db')  print d['abc']  d.close()

這個有一個潛在的小問題,如下:

>>> import shelve >>> s = shelve.open('test.dat') >>> s['x'] = ['a', 'b', 'c'] >>> s['x'].append('d') >>> s['x'] ['a', 'b', 'c'] 

存儲的d到哪里去了呢?其實很簡單,d沒有寫回,你把['a', 'b', 'c']存到了x,當你再次讀取s['x']的時候,s['x']只是一個拷貝,而你沒有將拷貝寫回,所以當你再次讀取s['x']的時候,它又從源中讀取了一個拷貝,所以,你新修改的內容并不會出現在拷貝中,解決的辦法就是,第一個是利用一個緩存的變量,如下所示

>>> temp = s['x'] >>> temp.append('d') >>> s['x'] = temp >>> s['x'] ['a', 'b', 'c', 'd'] 

在python2.4以后有了另外的方法,就是把open方法的writeback參數的值賦為True,這樣的話,你open后所有的內容都將在cache中,當你close的時候,將全部一次性寫到硬盤里面。如果數據量不是很大的時候,建議這么做。

下面是一個基于shelve的簡單數據庫的代碼

#database.py import sys, shelve  def store_person(db):   """   Query user for data and store it in the shelf object   """   pid = raw_input('Enter unique ID number: ')   person = {}   person['name'] = raw_input('Enter name: ')   person['age'] = raw_input('Enter age: ')   person['phone'] = raw_input('Enter phone number: ')   db[pid] = person  def lookup_person(db):   """   Query user for ID and desired field, and fetch the corresponding data from   the shelf object   """   pid = raw_input('Enter ID number: ')   field = raw_input('What would you like to know? (name, age, phone) ')   field = field.strip().lower()   print field.capitalize() + ':', /     db[pid][field]  def print_help():   print 'The available commons are: '   print 'store :Stores information about a person'   print 'lookup :Looks up a person from ID number'   print 'quit  :Save changes and exit'   print '?   :Print this message'  def enter_command():   cmd = raw_input('Enter command (? for help): ')   cmd = cmd.strip().lower()   return cmd  def main():   database = shelve.open('database.dat')   try:      while True:       cmd = enter_command()       if cmd == 'store':         store_person(database)       elif cmd == 'lookup':         lookup_person(database)       elif cmd == '?':         print_help()       elif cmd == 'quit':         return    finally:     database.close() if __name__ == '__main__': main() 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 威宁| 阳泉市| 武山县| 莲花县| 盘山县| 固安县| 若尔盖县| 酉阳| 宿迁市| 克东县| 浮山县| 沂水县| 胶南市| 台前县| 石台县| 乌拉特中旗| 朝阳区| 罗定市| 广昌县| 九龙城区| 益阳市| 甘泉县| 汤阴县| 棋牌| 南阳市| 大邑县| 甘孜| 理塘县| 丰原市| 耿马| 自治县| 柘城县| 贵港市| 仪征市| 鄂伦春自治旗| 高州市| 石林| 砚山县| 清原| 新营市| 甘泉县|