Details of python3 shelve module

  • 2020-06-12 09:33:51
  • OfStack

Details of python3 shelve module

1. Introduction

In python3, we use json or pickle to persist data, which can be dump multiple times, but only load1 time, because the previous data has been overwritten by the data of dump later. If we want to implement dump and load multiple times, we can use the shelve module. The shelve module can persist all data types supported by pickle.

2. Persist data

1. Data persistence


import shelve
import datetime
 
info = {'name': 'bigberg', 'age': 22}
name = ['Apoll', 'Zous', 'Luna']
t = datetime.datetime.now()
 
with shelve.open('shelve.txt') as f:
  f['name'] = name  #  Persistent list 
  f['info'] = info     #  Persistent dictionary 
  f['time'] = t      #  Persistent time type 
  

After executing the code, three files are generated: shelve.txt.bak, shelve.txt.dat, shelve.txt.dir.

The content of the 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.                                                                                                                                                                                                                                          �cdatetime
datetime
q C
�"
2�q�qRq.

The content of the shelve. txt. dir


'info', (512, 45)
'name', (0, 42)
'time', (1024, 44)

2. Data reading

We used get to get the data


import 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)
 
# The output 
 
['Apoll', 'Zous', 'Luna']
{'age': 22, 'name': 'bigberg'}
2017-07-08 11:07:34.865022
 

1, shelve module is a simple key, value memory data through the file persistence module.

2. shelve module can persist any python data format supported by pickle.

3. shelve is an encapsulation of pickle module.

4, shelve module can be dump and load for multiple times.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: