zoukankan      html  css  js  c++  java
  • 序列化模块_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))


  • 相关阅读:
    C++ 运行时类型识别 知道实例父类类型,显示出子类类型
    C++里面方便的打印日志到文件
    vs2015上配置Armadillo+openBlas
    opencl 在vs2015上遇见的问题
    Lucene子项目------------------Solr遇到的问题
    [LeetCode]Course Schedule
    [LeetCode]Minimum Size Subarray Sum
    [LeetCode]Reverse Linked List
    [LeetCode]Isomorphic Strings
    [LeetCode]Ugly Number
  • 原文地址:https://www.cnblogs.com/caihuajiaoshou/p/10639479.html
Copyright © 2011-2022 走看看