• python序列化


    一. 序列化

    1 定义: 在我们存储数据或者⽹网络传输数据的时候. 需要对我们的对象进⾏行行处理理. 把对象处理理成 ⽅方便便存储和传输的数据格式. 这个过程叫序列列化. 不同的序列列化, 结果也不同. 但是⽬目的是⼀一 样的. 都是为了了存储和传输.

    2 方案 :

         1. pickle. 可以将我们python中的任意数据类型转化成bytes并写入到⽂文件中.  同样也 可以把⽂文件中写好的bytes转换回我们python的数据. 这个过程被称为反序列列化   

    import pickle
    class Notebook:
        def __init__(self, page, size):
            self.page = page
            self.size =size
        def remenber(self):
            print("记录笔记!")
    
    n = Notebook(100, "A5")
    s = pickle.dumps(n)
    s_n = pickle.loads(s)
    print(s_n.page)
    
    with open("pick_test", mode="w+b") as f:
        pickle.dump(n, f)
        pickle.dump(n, f)
        f.seek(0)
        print(pickle.load(f).size)
        print(pickle.load(f).size)
    

            

         2. shelve. 简单另类的⼀一种序列列化的⽅方案. 有点⼉儿类似后⾯面我们学到的redis. 可以作为 ⼀一种⼩小型的数据库来使⽤用

    s = shelve.open("shel_test",writeback=True)
    s["a"] = "鲁迅"
    print(s["a"])
    s["a"] = "大白"  #  因有writeback=True, 所以可以直接改写文件
    print(s["a"])
    for i in s: # 和字典一样可以循环哪key和value
        print(i)
    s.close()
    

               

          3. json. 将python中常⻅见的字典, 列列表转化成字符串串. 是⽬目前前后端数据交互使⽤用频率 最⾼高的⼀一种数据格式.

    s = json.dumps(dic, ensure_ascii=False)
    print(s)
    print(type(s))
    re = json.loads(s, encoding="utf-8")
    print(re)
    print(type(re))
    print(re["演员"])
    
    with open("json_test", mode="w+",encoding="utf-8") as fj:
        json.dump(dic, fj, ensure_ascii=False)
        fj.write("
    ")
        json.dump(dic, fj, ensure_ascii=False)
    
    
    with open("json_test", mode="r", encoding="utf-8") as fr:
        st = fr.readline().strip()
        ret = json.loads(st, encoding="utf-8")
        print(ret)
        print(type(ret))
    

    configparser模块    该模块适⽤用于配置⽂文件的格式

    conf = configparser.ConfigParser()
    conf["DEFAULT"] = { "ip": "192.168.1.1",
                                "port": 3306
    
                       }
    
    conf["A"] = { "ip": "192.168.1.2",
                "port": 3306
    
                       }
    conf["B"] = { "ip": "192.168.1.2",
                "port": 3306
    
                       }
    conf["C"] = { "ip": "192.168.1.2",
                "port": 3306
    
                       }
    
    with open("configp_test", mode="w", encoding="utf-8") as f:
        conf.write(f)
    
    conf.read("configp_test")
    print(conf.sections()) # 拿到章节名
    print(conf.get("A", "ip"))  # 拿章节里面的ip
    for i in conf["A"]: # 循环章节
        print(i) # 打印章节 内容中的信息key
        print(conf["A"]["ip"]) # value
    
  • 相关阅读:
    UGO小组冲刺第一天
    day04_07-三个函数的区别
    day06_08 字符串
    day06_07 字典操作02
    day06_06 字典操作01
    day06_05 字典
    day06_04 购物车讲解02
    day06_03 购物车讲解01
    day06_02 元组
    day06_01 上节回顾
  • 原文地址:https://www.cnblogs.com/tcpblog/p/9763315.html
Copyright © 2020-2023  润新知