Python3-笔记-E-008-库-字典序列化shelve
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3-笔记-E-008-库-字典序列化shelve相关的知识,希望对你有一定的参考价值。
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()
以上是关于Python3-笔记-E-008-库-字典序列化shelve的主要内容,如果未能解决你的问题,请参考以下文章