shelve

'''
json和pickle模块的序列化和反序列化处理,有一个不足是在python3中不能多次dump和load, shelve模块则可以规避这个问题
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式, 是pickle更上一层的封装
'''

import shelve
import os


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data')
SH_DIR = os.path.join(DATA_DIR, 'sh.pkl')

if not os.path.exists(DATA_DIR):
    os.mkdir(DATA_DIR)

# 文件持久化, sh类似字典操作数据的方式
sh = shelve.open('data/sh.pkl')
sh['list'] = [1, 2, 3]

# writeback=False, need to code carefully
temp = sh['list']
temp.append(4)
sh['list'] = temp

print(sh['list'])

print(list(sh.keys()))
del sh['key']   # delete data stored at key (raises KeyError # if no such key)
print(list(sh.keys()))

sh.close()

Last updated