首页 > 编程语言 > 详细

Python3-笔记-E-008-库-字典序列化shelve

时间:2017-10-26 12:34:36      阅读:260      评论:0      收藏:0      [点我收藏+]
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

原文:http://www.cnblogs.com/vito13/p/7736000.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!