• 序列化 pickle shelve json configparser 023


    一. 序列化: 把对象处理成方便存储和传输的数据格式 过程叫序列化

      反序列化: 把bytes或者字符串转换回对象.反序列化

    二.pickle.将任意数据类型转化成bytes并写入到文件中 同样也可以转换回来 这个过程称反序列化.(重点

      dumps()  序列化 不写文件

      loads() 反序列化, 不读文件

    import pickle
    class Cat:
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def catchMouse(self):
            print(self.name,self.age,'抓老鼠')
    c = Cat('Tom',18)
    c.catchMouse() #Tom 18 抓老鼠
    bs = pickle.dumps(c)
    print(bs) # 机器语言b'x80x03c__main__
    Cat
    qx00)x81qx01}qx02(Xx04x00x00x00nameqx03Xx03x00x00x00Tomqx04Xx03x00x00x00ageqx05Kx12ub.'
    ccc = pickle.loads(bs)
    ccc.catchMouse() #Tom 18 抓老鼠

        dump 直接写入文件 序列化

        load 直接写入文件 反序列化

    三 .shelve 提供Python的持久化操作 把数据写到硬盘上(文件中)

        shelve.open(文件,writeback=True)

        有了writeback = True 这句话 就可以对源文件进行改.删

    四 .json 前后端交互的枢纽 相当于编程界普通话(重点)   把对象序列化成字符串

        前后端数据交互的通用的数据格式

        dumps() 把字典转化成字符串    往外传东西

        loads()   把字符串转化为字典 从网页上爬东西

        处理中文

          ensure_ascii = False

    五 .configparser 模块 全称(JavaSCript object notation)

        处理配置文件的

        把配置文件作为一个大字典来处理就行了.需要做的配置是将配置信息写到与配置文件同级的 文件名.ini 文件中

    [COMMON]
    host = 192.168.9.128
    root_dir = /work
    log_level = INFO
    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    window.ini

    接着在该目录下新建一个py文件进行读取

    try:
        import ConfigParser
    except:
        import configparser as ConfigParser
    class Config:
        def __init__(self):
            self.fpath = os.path.join(os.path.dirname(__file__).replace("\", "/"), "config.ini")
            self.cf = ConfigParser.ConfigParser()
            self.cf.read(self.fpath)
            self.COMMON_HOST = self.cf.get(COMMON, 'host')
            self.COMMON_LOG_LEVEL = self.cf.get(COMMON, 'log_level')
    
    config = Config()
    config.py

    接下来就是在需要引用的地方直接导入就可以了    from config import config

    config.COMMON_HOST 即调用了config.ini配置的host的地址 即 192.168.9.128

  • 相关阅读:
    redis-原理-数据结构-链表(二)
    redis-原理-数据结构-SDS(一)
    springMVC源码阅读-解决body不能重复读取问题(十二)
    spring-security使用-安全防护HttpFirewall(七)
    Redis-6.2.1 主从和哨兵模式配置
    Navicat 连接Mysql 8.0以上版本报错1251
    docker logs命令查看容器的日志
    Nginx 反向代理
    docker swarm 删除节点 (解散集群)
    Docker Swarm 命令学习
  • 原文地址:https://www.cnblogs.com/f-g-f/p/9759684.html
Copyright © 2020-2023  润新知