舉例簡單講解Python中的數(shù)據(jù)存儲模塊shelve的用法
shelve類似于一個key-value數(shù)據(jù)庫,可以很方便的用來保存Python的內(nèi)存對象,其內(nèi)部使用pickle來序列化數(shù)據(jù),簡單來說,使用者可以將一個列表、字典、或者用戶自定義的類實(shí)例保存到shelve中,下次需要用的時候直接取出來,就是一個Python內(nèi)存對象,不需要像傳統(tǒng)數(shù)據(jù)庫一樣,先取出數(shù)據(jù),然后用這些數(shù)據(jù)重新構(gòu)造一遍所需要的對象。下面是簡單示例:
import shelve def test_shelve(): # open 返回一個Shelf類的實(shí)例 # # 參數(shù)flag的取值范圍: # 'r':只讀打開 # 'w':讀寫訪問 # 'c':讀寫訪問,如果不存在則創(chuàng)建 # 'n':讀寫訪問,總是創(chuàng)建新的、空的數(shù)據(jù)庫文件 # # protocol:與pickle庫一致 # writeback:為True時,當(dāng)數(shù)據(jù)發(fā)生變化會回寫,不過會導(dǎo)致內(nèi)存開銷比較大 d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False) assert isinstance(d, shelve.Shelf) # 在數(shù)據(jù)庫中插入一條記錄 d['abc'] = {'name': ['a', 'b']} d.sync() print d['abc'] # writeback是False,因此對value進(jìn)行修改是不起作用的 d['abc']['x'] = 'x' print d['abc'] # 還是打印 {'name': ['a', 'b']} # 當(dāng)然,直接替換key的value還是起作用的 d['abc'] = 'xxx' print d['abc'] # 還原abc的內(nèi)容,為下面的測試代碼做準(zhǔn)備 d['abc'] = {'name': ['a', 'b']} d.close() # writeback 為 True 時,對字段內(nèi)容的修改會writeback到數(shù)據(jù)庫中。 d = shelve.open('shelve.db', writeback=True) # 上面我們已經(jīng)保存了abc的內(nèi)容為{'name': ['a', 'b']},打印一下看看對不對 print d['abc'] # 修改abc的value的部分內(nèi)容 d['abc']['xx'] = 'xxx' print d['abc'] d.close() # 重新打開數(shù)據(jù)庫,看看abc的內(nèi)容是否正確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到哪里去了呢?其實(shí)很簡單,d沒有寫回,你把['a', 'b', 'c']存到了x,當(dāng)你再次讀取s['x']的時候,s['x']只是一個拷貝,而你沒有將拷貝寫回,所以當(dāng)你再次讀取s['x']的時候,它又從源中讀取了一個拷貝,所以,你新修改的內(nèi)容并不會出現(xiàn)在拷貝中,解決的辦法就是,第一個是利用一個緩存的變量,如下所示
>>> temp = s['x'] >>> temp.append('d') >>> s['x'] = temp >>> s['x'] ['a', 'b', 'c', 'd']
在python2.4以后有了另外的方法,就是把open方法的writeback參數(shù)的值賦為True,這樣的話,你open后所有的內(nèi)容都將在cache中,當(dāng)你close的時候,將全部一次性寫到硬盤里面。如果數(shù)據(jù)量不是很大的時候,建議這么做。
下面是一個基于shelve的簡單數(shù)據(jù)庫的代碼
#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()
- 詳解Python中如何將數(shù)據(jù)存儲為json格式的文件
- Python 抓取數(shù)據(jù)存儲到Redis中的操作
- Python數(shù)據(jù)存儲之 h5py詳解
- python將類似json的數(shù)據(jù)存儲到MySQL中的實(shí)例
- python3爬蟲學(xué)習(xí)之?dāng)?shù)據(jù)存儲txt的案例詳解
- Python使用shelve模塊實(shí)現(xiàn)簡單數(shù)據(jù)存儲的方法
- 將Python中的數(shù)據(jù)存儲到系統(tǒng)本地的簡單方法
- Python實(shí)現(xiàn)疫情地圖可視化
- python如何繪制疫情圖
- python+selenium 簡易地疫情信息自動打卡簽到功能的實(shí)現(xiàn)代碼
- Python實(shí)現(xiàn)疫情通定時自動填寫功能(附代碼)
- Python繪制全球疫情變化地圖的實(shí)例代碼
- Python爬蟲爬取全球疫情數(shù)據(jù)并存儲到mysql數(shù)據(jù)庫的步驟
相關(guān)文章
基于Python實(shí)現(xiàn)開發(fā)釘釘通知機(jī)器人
在項(xiàng)目協(xié)同工作或自動化流程完成時,我們需要用一定的手段通知自己或他人。Telegram 非常好用,幾個步驟就能創(chuàng)建一個機(jī)器人,可惜在國內(nèi)無法使用。所以本文就來開發(fā)一個釘釘通知機(jī)器人吧2023-02-02Python面向?qū)ο缶幊剃P(guān)鍵深度探索類與對象
這篇文章主要為大家介紹了Python面向?qū)ο缶幊剃P(guān)鍵深度探索類與對象示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05python中浮點(diǎn)數(shù)比較判斷!為什么不能用==(推薦)
這篇文章主要介紹了python中浮點(diǎn)數(shù)比較判斷!為什么不能用==,本文給大家分享問題解決方法,需要的朋友可以參考下2023-09-09python常見數(shù)制轉(zhuǎn)換實(shí)例分析
這篇文章主要介紹了python常見數(shù)制轉(zhuǎn)換,實(shí)例分析了二進(jìn)制、八進(jìn)制、十進(jìn)制及十六進(jìn)制之間的相互轉(zhuǎn)換技巧,需要的朋友可以參考下2015-05-05Python批量將Word文件轉(zhuǎn)為PDF文件的實(shí)現(xiàn)示例
如果想要批量把Word文檔轉(zhuǎn)換為PDF文檔,我們可以使用第三方模塊win32com,本文就來詳細(xì)的介紹一下Python批量將Word文件轉(zhuǎn)為PDF文件的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-08-08Python實(shí)現(xiàn)簡單拆分PDF文件的方法
這篇文章主要介紹了Python實(shí)現(xiàn)簡單拆分PDF文件的方法,可實(shí)現(xiàn)將一個PDF文件拆分成指定份數(shù)的功能,涉及pyPdf模塊的使用技巧,需要的朋友可以參考下2015-07-07