python shelve 模組

來源:互聯網
上載者:User

標籤:持久   封裝   print   json   資料格式   記憶體資料   覆蓋   一個   pre   

一、簡介  在python3中我們使用json或者pickle持久化資料,能dump多次,但只能load一次,因為先前的資料已經被後面dump的資料覆蓋掉了。如果我們想要實現dump和load多次,可以使用shelve模組。shelve模組可以持久化所有pickle所支援的資料類型。
代碼:

 

#持久化資料import shelveimport datetime# info = {‘name‘: ‘bigberg‘, ‘age‘: 22}# name = [‘Apoll‘, ‘Zous‘, ‘Luna‘]# t = datetime.datetime.now()## with shelve.open(‘shelve.txt‘) as f:#     f[‘name‘] = name  # 持久化列表#     f[‘info‘] = info  # 持久化字典#     f[‘time‘] = t  # 持久化時間類型## # 執行代碼後會產生3個檔案:shelve.txt.bak、shelve.txt.dat、shelve.txt.dir。#刪除# with shelve.open(‘shelve.txt‘) as f:#     del f[‘name‘]#擷取資料:用getimport shelve# with shelve.open(‘shelve.txt‘) as f:#     n = f.get(‘name‘)#     i = f.get(‘info‘)#     now = f.get(‘time‘)## print(n)# print(i)# print(now)# 輸出
總結:

 

1、shelve模組是一個簡單的key,value將記憶體資料通過檔案持久化的模組。2、shelve模組可以持久化任何pickle可支援的python資料格式。3、shelve就是pickle模組的一個封裝。4、shelve模組是可以多次dump和load。

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.