import shelve
# shelve_demo.py 持久性字典:Python对象的持久化
# 键值对形式, 将内存数据通过文件持久化, 值支持任何pickle支持的Python数据格式
# 与pickle的主要区别是键值对方式, 并且在目录下生成三个文件
class Person(object):
def __init__(self):
self.name = "luzhuo"
self.age = 21
def __str__(self):
return "name: {}, age: {}".format(self.name, self.age)
path = "shelve_demo.txt"
def shelve_write():
'''
序列化
'''
with shelve.open(path) as write: # 打开
write["nums"] = [1, 2, 3, 4, 5] # 写
write["obj"] = Person()
def shelve_read():
'''
反序列化
'''
with shelve.open(path) as read: # 打开
nums = read.get("nums") # 读取
print(nums)
clazz = read["obj"]
print(clazz)
del read["obj"] # 删除
print("obj" in read)
keys = list(read.keys()) # 所有key
print(keys)
shelve_write()
shelve_read()