shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
shelve对pickle进行了封装,允许你dump多次,并且顺序不会乱。所以,能用shevel就用shevel,不能用就用pickle,pickle不能用再用json。
序列化:
import shelvef = shelve.open('shelve_test') # 打开一个文件names = ["alex", "rain", "test"]info = {'name':'alex','age':22}f["names"] = names # 持久化列表f['info_dic'] = infof.close()
反序列化:
import shelved = shelve.open('shelve_test') # 打开一个文件print(d['names'])print(d['info_dic'])#del d['test'] #还可以删除
代码示例:
# 对pickle进行了封装,允许你dump多次,并且顺序不会乱。import shelvef = shelve.open('shevel_test') # 打开一个文件info = { 'name': 'alex', 'age': 22}names = ['alex', 'rain', 'test']f['names'] = namesf['info_dic'] = infof.close() # 也是存的一推乱码with shelve.open('shevel_test') as f: print(f) #print(f.keys()) # KeysView( ) print(list(f.keys())) # ['names', 'info_dic'] print(f.items()) # ItemsView( ) print(f.get('names')) # ['alex', 'rain', 'test'] print(f.get('info_dic')) # {'name': 'alex', 'age': 22} f['names'] = ['Rain', 'Ann', 'Jack'] # ['Rain', 'Ann', 'Jack'] print(f.get('names'))