舉例簡(jiǎn)單講解Python中的數(shù)據(jù)存儲(chǔ)模塊shelve的用法
shelve類似于一個(gè)key-value數(shù)據(jù)庫(kù),可以很方便的用來(lái)保存Python的內(nèi)存對(duì)象,其內(nèi)部使用pickle來(lái)序列化數(shù)據(jù),簡(jiǎn)單來(lái)說(shuō),使用者可以將一個(gè)列表、字典、或者用戶自定義的類實(shí)例保存到shelve中,下次需要用的時(shí)候直接取出來(lái),就是一個(gè)Python內(nèi)存對(duì)象,不需要像傳統(tǒng)數(shù)據(jù)庫(kù)一樣,先取出數(shù)據(jù),然后用這些數(shù)據(jù)重新構(gòu)造一遍所需要的對(duì)象。下面是簡(jiǎn)單示例:
import shelve
def test_shelve():
# open 返回一個(gè)Shelf類的實(shí)例
#
# 參數(shù)flag的取值范圍:
# 'r':只讀打開
# 'w':讀寫訪問(wèn)
# 'c':讀寫訪問(wèn),如果不存在則創(chuàng)建
# 'n':讀寫訪問(wèn),總是創(chuàng)建新的、空的數(shù)據(jù)庫(kù)文件
#
# protocol:與pickle庫(kù)一致
# writeback:為True時(shí),當(dāng)數(shù)據(jù)發(fā)生變化會(huì)回寫,不過(guò)會(huì)導(dǎo)致內(nèi)存開銷比較大
d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False)
assert isinstance(d, shelve.Shelf)
# 在數(shù)據(jù)庫(kù)中插入一條記錄
d['abc'] = {'name': ['a', 'b']}
d.sync()
print d['abc']
# writeback是False,因此對(duì)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)容,為下面的測(cè)試代碼做準(zhǔn)備
d['abc'] = {'name': ['a', 'b']}
d.close()
# writeback 為 True 時(shí),對(duì)字段內(nèi)容的修改會(huì)writeback到數(shù)據(jù)庫(kù)中。
d = shelve.open('shelve.db', writeback=True)
# 上面我們已經(jīng)保存了abc的內(nèi)容為{'name': ['a', 'b']},打印一下看看對(duì)不對(duì)
print d['abc']
# 修改abc的value的部分內(nèi)容
d['abc']['xx'] = 'xxx'
print d['abc']
d.close()
# 重新打開數(shù)據(jù)庫(kù),看看abc的內(nèi)容是否正確writeback
d = shelve.open('shelve.db')
print d['abc']
d.close()
這個(gè)有一個(gè)潛在的小問(wèn)題,如下:
>>> import shelve
>>> s = shelve.open('test.dat')
>>> s['x'] = ['a', 'b', 'c']
>>> s['x'].append('d')
>>> s['x']
['a', 'b', 'c']
存儲(chǔ)的d到哪里去了呢?其實(shí)很簡(jiǎn)單,d沒(méi)有寫回,你把['a', 'b', 'c']存到了x,當(dāng)你再次讀取s['x']的時(shí)候,s['x']只是一個(gè)拷貝,而你沒(méi)有將拷貝寫回,所以當(dāng)你再次讀取s['x']的時(shí)候,它又從源中讀取了一個(gè)拷貝,所以,你新修改的內(nèi)容并不會(huì)出現(xiàn)在拷貝中,解決的辦法就是,第一個(gè)是利用一個(gè)緩存的變量,如下所示
>>> 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í)候,將全部一次性寫到硬盤里面。如果數(shù)據(jù)量不是很大的時(shí)候,建議這么做。
下面是一個(gè)基于shelve的簡(jiǎn)單數(shù)據(jù)庫(kù)的代碼
#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ù)存儲(chǔ)為json格式的文件
- Python 抓取數(shù)據(jù)存儲(chǔ)到Redis中的操作
- Python數(shù)據(jù)存儲(chǔ)之 h5py詳解
- python將類似json的數(shù)據(jù)存儲(chǔ)到MySQL中的實(shí)例
- python3爬蟲學(xué)習(xí)之?dāng)?shù)據(jù)存儲(chǔ)txt的案例詳解
- Python使用shelve模塊實(shí)現(xiàn)簡(jiǎn)單數(shù)據(jù)存儲(chǔ)的方法
- 將Python中的數(shù)據(jù)存儲(chǔ)到系統(tǒng)本地的簡(jiǎn)單方法
- Python實(shí)現(xiàn)疫情地圖可視化
- python如何繪制疫情圖
- python+selenium 簡(jiǎn)易地疫情信息自動(dòng)打卡簽到功能的實(shí)現(xiàn)代碼
- Python實(shí)現(xiàn)疫情通定時(shí)自動(dòng)填寫功能(附代碼)
- Python繪制全球疫情變化地圖的實(shí)例代碼
- Python爬蟲爬取全球疫情數(shù)據(jù)并存儲(chǔ)到mysql數(shù)據(jù)庫(kù)的步驟
相關(guān)文章
Python Django 添加首頁(yè)尾頁(yè)上一頁(yè)下一頁(yè)代碼實(shí)例
這篇文章主要介紹了Python Django 添加首頁(yè)尾頁(yè)上一頁(yè)下一頁(yè)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Python Sanic框架實(shí)現(xiàn)文件上傳功能
Sanic是一個(gè)Python 3.5+的異步Web框架,它的設(shè)計(jì)理念與Flask相似,但采用了更高效的異步I/O處理,在處理文件上傳時(shí),Sanic同樣提供了方便、高效的方法,本教程將結(jié)合實(shí)際案例,詳細(xì)介紹如何在Sanic框架中實(shí)現(xiàn)文件上傳的功能,需要的朋友可以參考下2024-08-08
Python獲取網(wǎng)段內(nèi)ping通IP的方法
今天小編就為大家分享一篇Python獲取網(wǎng)段內(nèi)ping通IP的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
Python程序設(shè)計(jì)入門(2)變量類型簡(jiǎn)介
這篇文章主要介紹了Python變量類型,需要的朋友可以參考下2014-06-06
python將字符串list寫入excel和txt的實(shí)例
今天小編就為大家分享一篇python將字符串list寫入excel和txt的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python自動(dòng)安裝第三方庫(kù)的小技巧(pip使用詳解)
很多朋友私信小編Python安裝第三方庫(kù)安裝技巧,在這就不一一回復(fù)大家了,今天小編給大家分享一篇教程關(guān)于Python自動(dòng)安裝第三方庫(kù)的小技巧,本文以安裝plotly為例給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧2021-05-05

