zoukankan      html  css  js  c++  java
  • 27-1 序列化模块 pickle

    python专用

    没什么限制

    能处理很多数据类型!

    dump 需要的文件f句柄 需要wb形式打开,load需要rb模式

    支持对象序列化!需要这个对象对应的类在内存中

    转成bytes类型!也是序列类型

    dic = {1:(12,3,4),('a','b'):4}
    import pickle
    
    pic_dic = pickle.dumps(dic)
    print(pic_dic)    # bytes类型  b'x80x04x95x1bx00x00x00x.... 
    new_dic = pickle.loads(pic_dic)
    print(new_dic)    # {1: (12, 3, 4), ('a', 'b'): 4}
    支持几乎所有对象的
    class Student:
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
    alex = Student('alex',83)
    ret = pickle.dumps(alex)
    小花 = pickle.loads(ret)
    print(小花.name)  
    print(小花.age)
    class Student:
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
    alex = Student('alex',83)
    with open('pickle_demo','wb') as f:
        pickle.dump(alex,f)
    with open('pickle_demo','rb') as f:
        旺财 = pickle.load(f)
        print(旺财.name)
    View Code
    这种方式可以重复写入,然后重复拿出来(这里有一个异常,在最后一次没有值,会报错,这里用了异常处理)
    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


  • 相关阅读:
    做了6年开发,工资涨不上去,怎么办?(安晓辉,循循善诱的分析)
    Hello World
    服务治理框架
    Range锁(也即范围锁)
    C# .NET Socket
    Net Core应用,在CentOS上运行
    分布式锁,进程锁,线程锁
    TEMPDB
    学会Git
    Docker
  • 原文地址:https://www.cnblogs.com/zhuangdd/p/12657017.html
Copyright © 2011-2022 走看看