• 序列化模块注意点 json&pickle


     
    dic = {'k1':'v1'}
    print(type(dic),dic)
    import json
    str_d = json.dumps(dic)
    print(type(str_d),str_d)
    
    dic_d = json.loads(str_d)
    print(type(dic_d),dic_d)

    结果:

    <class 'dict'> {'k1': 'v1'}
    <class 'str'> {"k1": "v1"}
    <class 'dict'> {'k1': 'v1'}
    import json
    dic = {'k1':'v1'}
    f = open('fff','w',encoding='UTF-8')
    json.dump(dic,f)
    f.close()
    
    f = open(file = 'fff',mode = 'r',encoding='UTF-8')
    res = json.load(f)
    f.close()
    print(type(res),res)

    结果:

    <class 'dict'> {'k1': 'v1'}

    并且生成一个文件,filename为fff,里面保存了一个dic

     json

    ----end----

    import pickle
    dic = {'k1':'v1','k2':'v2','k3':'v3'}
    str_dic = pickle.dumps(dic)
    print(str_dic)
    dic2 = pickle.loads(str_dic)
    print(dic2)

    结果:

    b'x80x03}qx00(Xx02x00x00x00k1qx01Xx02x00x00x00v1qx02Xx02x00x00x00k2qx03Xx02x00x00x00v2qx04Xx02x00x00x00k3qx05Xx02x00x00x00v3qx06u.'
    {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
    import pickle
    import time
    struct_time = time.localtime(10000000)
    print(struct_time)
    f = open('pickle_file','wb')
    pickle.dump(struct_time,f)
    f.close()
    f = open('pickle_file','rb')
    struct_time2 = pickle.load(f)
    print(struct_time2)

    结果:

    time.struct_time(tm_year=1970, tm_mon=4, tm_mday=27, tm_hour=1, tm_min=46, tm_sec=40, tm_wday=0, tm_yday=117, tm_isdst=0)
    time.struct_time(tm_year=1970, tm_mon=4, tm_mday=27, tm_hour=1, tm_min=46, tm_sec=40, tm_wday=0, tm_yday=117, tm_isdst=0)

    会生成一个文件.然而并看不懂文件里面写的什么

    pickle

    ----end----

    dumps&loads

    序列化&反序列化(对内存操作)

    dump&load

    (对文件操作)

    
    
  • 相关阅读:
    SQL Server中使用convert进行日期转换
    杂记
    sqlserver表分区与调优与行列转换
    HttpModule的认识与深入理解及MVC运行机制
    再谈委托
    ASP.NET forms凭据设置和跳转的几种方法
    IOS学习网址
    Activator.CreateInstance 方法 (Type) 的用法
    update多表更新的2种方式
    SQL自定义函数split分隔字符串
  • 原文地址:https://www.cnblogs.com/Hxx0916/p/9602012.html
Copyright © 2020-2023  润新知