shelve模組,pythonshelve模組

來源:互聯網
上載者:User

shelve模組,pythonshelve模組
一、簡介

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

二、持久化資料1、資料持久化
import shelveimport datetimeinfo = {'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。

  • shelve.txt.bak 的內容
'info', (512, 45)'name', (0, 42)'time', (1024, 44)
  • shelve.txt.dat  
�]q (X   ApollqX   ZousqX   Lunaqe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      �}q (X   ageqKX   nameqX   bigbergqu.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   �cdatetimedatetimeq C�"2�q�qRq.
  • shelve.txt.dir 的內容
'info', (512, 45)'name', (0, 42)'time', (1024, 44)

  

2、資料讀取

我們使用get來擷取資料

import shelvewith shelve.open('shelve.txt') as f:    n = f.get('name')    i = f.get('info')    now = f.get('time')print(n)print(i)print(now)#輸出['Apoll', 'Zous', 'Luna']{'age': 22, 'name': 'bigberg'}2017-07-08 11:07:34.865022

 

1、shelve模組是一個簡單的key,value將記憶體資料通過檔案持久化的模組。

2、shelve模組可以持久化任何pickle可支援的python資料格式。

3、shelve就是pickle模組的一個封裝。

4、shelve模組是可以多次dump和load。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.