zoukankan      html  css  js  c++  java
  • IO编程----序列化

    pickle

    import pickle
    
    d={'name':'Bob','age':20,'score':88}
    
    '''
    pickle.dump直接将对象序列化并写入一个file-like Object
    '''
    with open('dump.txt','wb') as f:
        pickle.dump(d,f)
    
    
    '''
    pickle.load()方法从一个file-like Object中直接反序列化出对象
    '''
    with open('dump.txt','rb') as f:
        d=pickle.load(f)
        print(d)

    Json

    import json
    
    d={'name':'Bob','age':20,'score':88}
    
    with open('testJson','w') as f:
        json.dump(d,f)
    
    with open('testJson','r') as f:
        print(json.load(f))

    Json高级进阶

    import json
    
    d={'name':'Bob','age':20,'score':88}
    
    with open('testJson','w') as f:
        json.dump(d,f)
    
    with open('testJson','r') as f:
        print(json.load(f))
    
    
    
    obj = dict(name='小明', age=20)
    #ensure_ascii=True,值为True,则序列化保存为ascii码,为False,保存为原始编码
    s = json.dumps(obj, ensure_ascii=True)
    print(s)
    
    #一般情况下,我们会序列化类对象
    class student(object):
        def __init__(self,name,age,score):
            self.name=name
            self.age=age
            self.score=score
    
    s=student('wangxy',20,88)
    
    '''
    json.dumps(s)直接序列化对象会输出,
    raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: <__main__.student object at 0x7fa705cf05f8> is not JSON serializable
    '''
    
    #dump和dumps方法中的可选参数default就是把任意一个对象变成一个可序列为JSON的对象
    def studentToDict(stu):
        return {
            'name':stu.name,
            'age':stu.age,
            'score':stu.score
        }
    
    with open('classToJson','w') as f:
        json.dump(s,f,default=studentToDict)
    
    #将json反序列化为类对象实例
    def dictToStudent(d):
        return student(d['name'],d['age'],d['score'])
    
    with open('classToJson','r') as f:
        print(json.load(f,object_hook=dictToStudent))
    
    #通常情况下,class类都有一个__dict__,它就是dict,用来存储实例变量,
    print(json.dumps(s,default=lambda obj:obj.__dict__))


    输出:

    {'name': 'Bob', 'score': 88, 'age': 20}
    {"name": "u5c0fu660e", "age": 20}
    <__main__.student object at 0x7f7ac4a906d8>
    {"name": "wangxy", "age": 20, "score": 88}

  • 相关阅读:
    426 根据gop 讲解x264整个过程
    426 x264全局 完整有些东西还没理解
    SAD SATD转过来的
    帧内预测1
    4.1总结
    426 大话dct
    426 pixel赋值问题 mbcmp函数 宏定义
    426 pts dts
    每天进步一点点IAR for ARM_V6.30.1
    每天进步一点点NIOS II按键中断程序
  • 原文地址:https://www.cnblogs.com/wangxy92/p/8084807.html
Copyright © 2011-2022 走看看