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

    序列化 把对象打散成二进制字节 bytes
    1. pickle 把一个对象转化成bytes写入到文件
    pickle.dumps() 把对象转换成bytes
    pickle.loads() 把bytes转化成对象

    pickle.dump() 把对象转换成bytes. 写入到文件
    pickle.load() 把文件中的bytes读取. 转化成对象

    2. shelve 小型数据库, redis, mongodb, dict
    当成字典来用
    writeback=True

    import shelve

    # d = shelve.open("sylar") # 文件类型的字典
    # d['wf'] = "汪峰"
    # d.close()
    #
    # d = shelve.open("sylar")
    # print(d['wf'])
    # d.close()

    # d = shelve.open("sylar") # 文件类型的字典
    # d['wf'] = {"name":"汪峰", "age": 18, "wife":{"name":"章子怡", "hobby":"拍电影"}}
    # d.close()

    # d = shelve.open("sylar", writeback=True) # 文件类型的字典 wirteback把修改的内容自动的回写到文件中
    # d['wf']['wife']['hobby'] = "当导师" # 改
    # d.close()

    # d = shelve.open("sylar") # 文件类型的字典
    # print(d['wf'])
    # d.close()

    3. json 以前用xml 先在用json
    json.dumps() 把字典转换成json字符串
    json.loads() 把json字符串转化成字典

    json.dump() 把字典转换成json字符串. 写入到文件
    json.load() 把文件中的json字符串读取. 转化成字典

    dic1 = {"name":'毒液', "评分": "0.9"}
    dic2 = {"name":'与神同行', "评分": "10"}
    dic3 = {"name":'看不见的客人', "评分": "9.5"}

    # lst = [dic1, dic2, dic3]
    # f = open("movie.json", mode="w", encoding="utf-8")
    # for d in lst:
    # s = json.dumps(d, ensure_ascii=False)
    # f.write(s+" ")

    # f = open("movie.json", mode="r", encoding="utf-8")
    # dic1 = json.load(f) # 当json文件中保存多个json的时候不能一次性全部都读取出来
    # print(dic1)

    default = 把对象转化成字典. 需要自己写转换过程
    object_hook = 把字典转化成对象. 需要自己写转换过程

    ensure_ascii = False 可以处理中文

    # # 准备一个字典
    # dic = {"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": False, "e": None}
    # # python中可以直接把字典或者列表转化成json
    # s = json.dumps(dic, ensure_ascii=False) # pickle
    # print(type(s))
    # print(s)

    # s = '{"a": "小萝莉", "b": "大萝莉", "c": "猥琐大叔", "d": false, "e": null}'
    # d = json.loads(s) # 把json转化成字典
    # print(d)
    # print(type(d))


    4. configparser 处理windows配置文件的 dict

  • 相关阅读:
    善战者无赫赫之功,善医者无煌煌之名
    得到一个空值
    涡轮五字诀
    自定义的泛型类和泛型约束
    数据的格式化
    纸上得来终觉浅,绝知此事要躬行
    DateTime有默认构造函数吗?
    委托,语言级别的设计模式
    有想象力才有进步
    初始的设计思路
  • 原文地址:https://www.cnblogs.com/wwjx/p/9974705.html
Copyright © 2011-2022 走看看