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