zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    1059 C语言竞赛
    1058 选择题
    1057 数零壹
    1056 组合数的和
    1055 集体照
    Mysql--分库分表
    Mysql--改表结构
    Mysql--开始阶段
    Mysql--常用语句
    Mysql--grant授权
  • 原文地址:https://www.cnblogs.com/vito13/p/7736000.html
Copyright © 2011-2022 走看看