• 序列化模块_pickle


    序列化:

    把不能够直接存储的数据变成字节流(bytes)保存在文件,

    进行持久化存储

    反序列化:

    任何数据都可以转成字节流(bytes)进行存储:

    1. dumps

    把任意对象序列化

    1 li = [1, 2, 4]
    2 res = pickle.dumps(li)
    3 
    4 # 返回bytes
    5 print(res, type(res))

    2. loads

    把字节流转换为原本的数据

    1 li1 = pickle.loads(res)
    2 
    3 # 转换回的数据类型为list
    4 print(li1, type(li1))

    3. dump(obj, f)

    将数据写入文件

    1 with open('1.txt', 'wb') as f:
    2    li = [1, 2, 4, 5]
    3 
    4    # 将li转换成bytes, 使用f句柄写入文件, 没有返回值
    5    pickle.dump(li, f)

    4. load(f)

    读取写入文件中的字节流数据, 并将其转换成原本的数据

    1 with open('1.txt', 'rb') as f:
    2    res = pickle.load(f)
    3 
    4    # 读取f中写入的数据对象, 将bytes转换成原本的数据类型
    5    print(res, type(res))

    序列化迭代器

    1 iter1 = iter(range(5))
    2 res = pickle.dumps(iter1)
    3 
    4 iter2 = pickle.loads(res)
    5 print(iter2, type(iter2))

    多数据对象使用pickle写入文件

     1 li = [1, 2, 4, 5]
     2 tup = (1, 2, 4, 5)
     3 dic = {1:2, 2:3, 4:3}
     4 s = 'abc'
     5 setvar = {1, 2, 4}
     6 
     7 with open('2.txt', 'wb') as f:
     8    pickle.dump(li, f)
     9    pickle.dump(tup, f)
    10    pickle.dump(setvar, f)
    11    pickle.dump(dic, f)
    12    pickle.dump(s, f)
    13 
    14 
    15 with open('2.txt', 'rb') as f:
    16    # f也是一个迭代器,
    17    # load相当于next, 不断调用f
    18    # 返回反序列化后的数据
    19    for i in range(5):
    20       res = pickle.load(f)
    21       print(res, type(res))


  • 相关阅读:
    Vue less使用scope时渗入修改子组件样式
    Spring容器初始话原理图
    Java的动态代理
    Spring_xml和注解混合方式开发
    Spring_xml方式开发
    Spring入门初体验
    数论
    虚拟IP和IP漂移
    字符串hash + 二分答案
    字符串hash
  • 原文地址:https://www.cnblogs.com/caihuajiaoshou/p/10639479.html
Copyright © 2020-2023  润新知