zoukankan      html  css  js  c++  java
  • python-- pickle 序列化

    pickle

    dump的结果是bytes, dump用的f文件句柄需要以wb的形式打开, load所用的f是'rb'模式

    • 支持几乎所有对象的序列化
    • 对于对象的序列化需要这个对象对应的类在内存中
    • 对于多次dump / load的操作做了良好的处理
    import pickle
    
    dic = {1: (12, 3, 4), ('a', 'b'): 4}
    pic_dic = pickle.dumps(dic)
    print(pic_dic)  # bytes类型
    new_dic = pickle.loads(pic_dic)
    print(new_dic)

    结果:

    b'x80x03}qx00(Kx01Kx0cKx03Kx04x87qx01Xx01x00x00x00aqx02Xx01x00x00x00bqx03x86qx04Kx04u.'
    {1: (12, 3, 4), ('a', 'b'): 4}
    pickle支持几乎所有对象的
    import pickle
    
    
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    zou = Student('aa', 22)
    ret = pickle.dumps(zou)
    pickle_data = pickle.loads(ret)
    print(pickle_data.name)
    print(pickle_data.age)

    结果:

    aa
    22

    import pickle
    
    
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    zou = Student('aaa', 83)
    with open('pickle_demo', 'wb') as f:
        pickle.dump(zou, f)
    with open('pickle_demo', 'rb') as f:
        pic = pickle.load(f)
        print(pic.name)  # 没有上面的类就会报错,因为句话是从实例化类里拿name属性

    结果:

    aaa

    import pickle
    
    with open('pickle_demo', 'wb') as f:
        pickle.dump({'k1': 'v1'}, f)
        pickle.dump({'k11': 'v1'}, f)
        pickle.dump({'k11': 'v1'}, f)
        pickle.dump({'k12': [1, 2, 3]}, f)
        pickle.dump(['k1', 'v1', 'l1'], f)
    
    with open('pickle_demo', 'rb') as f:
        while True:
            try:
                print(pickle.load(f))
            except EOFError:
                break

    结果:

    {'k1': 'v1'}
    {'k11': 'v1'}
    {'k11': 'v1'}
    {'k12': [1, 2, 3]}
    ['k1', 'v1', 'l1']

  • 相关阅读:
    搭建DHCP服务
    sshd免密登陆
    加密类型以及数据加密解密过程
    搭建私有CA并实现证书颁发
    CentOS 7 启动流程
    Linux命令:tcpdump命令
    Linux命令:ping命令
    Linux命令:ss命令
    Linux命令:ip命令
    Linux命令:netstat命令
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/13702582.html
Copyright © 2011-2022 走看看