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

    (对文件操作)

    
    
  • 相关阅读:
    EasyUI tab
    CC和他的AE86
    Spreading the Wealth UVA
    Ultra-QuickSort POJ
    区间完全覆盖问题(贪心)
    Mod Tree HDU
    Snakes and Ladders LightOJ
    There is no SSR CSU
    X问题 HDU
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/Hxx0916/p/9602012.html
Copyright © 2011-2022 走看看