Shelve module and pythonshelve Module
I. Introduction
In python3, we use json or pickle for persistent data, which can be dumped multiple times, but can only be loaded once, because the previous data has been overwritten by the subsequent dump data. If you want to implement dump and load multiple times, you can use the shelve module. The shelve module can persist all data types supported by pickle.
Ii. persistent data 1. Data Persistence
Import shelveimport datetimeinfo = {'name': 'bigberg ', 'age': 22} name = ['poll', 'zous', 'luna'] t = datetime. datetime. now () with shelve.open('shelve.txt ') as f: f ['name'] = name # persistence list f ['info'] = info # persistence dictionary f ['time'] = t # persistence time type
After the code is executed, three files are generated: shelve.txt.bak?shelve.txt.dat=shelve.txt. dir.
- Content of shelve.txt. bak
'info', (512, 45)'name', (0, 42)'time', (1024, 44)
�]q (X ApollqX ZousqX Lunaqe. �}q (X ageqKX nameqX bigbergqu. �cdatetimedatetimeq C�"2�q�qRq.
- Contents of shelve.txt. dir
'info', (512, 45)'name', (0, 42)'time', (1024, 44)
2. Data Reading
We use get to get data.
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) # output ['poll', 'zous', 'luna '] {'age': 22, 'name': 'bigberg '} 11:07:34. 865022
1. The shelve module is a simple key. value stores the memory data through the file persistence module.
2. The shelve module can persist any python data formats supported by pickle.
3. shelve is an encapsulation of the pickle module.
4. The shelve module supports multiple dump and load operations.