• 常用模块——configparser模块


    configparser模块

    用于解析配置文件的模块
    何为配置文件
    包含配置程序信息的文件就称为配置文件
    什么样的数据应作为配置信息
    需要改 但是不经常改的信息 例如数据文件的路径 DB_PATH

    配置文件中 只有两种内容

    种是section 分区
    一种是option 选项 就是一个key=value形式
    我们用的最多的就是get功能 用来从配置文件获取一个配置选项

    读取cfg文件的步骤
    #创建一个解析器
    config = configparser.ConfigParser()
    # 读取并解析test.cfg
    config.read('test.cfg',encoding='utf-8')
    #获得分区
    print(config.sections())
    #获得’path'分区下选项
    print(config.options('path'))
    #['path', 'user']
    #['dp_file']
    #获取某分区的某选项的值
    print(config.get("path","dp_file"))
    print(type(config.get("user","age")))
    # # get返回的都是字符串类型  如果需要转换类型 直接使用get+对应的类型(bool int float)
    print(type(config.getint("user","age")))
    print(type(config.get("user","age")))

    不常用

    # 是否由某个选项
    config.has_option()
    # 是否由某个分区
    config.has_section()
    # 添加
    config.add_section("server")
    config.set("server","url","192.168.1.2")
    # 删除
    config.remove_option("user","age")
    # 修改
    config.set("server","url","192.168.1.2")
    # 写回文件中
    with open("test.cfg", "wt", encoding="utf-8") as f:
        config.write(f)
  • 相关阅读:
    英语_词汇_同意辨析
    英语_网站_写作工具
    英语词汇_难词易忘
    IDEA配置技巧 | 去除idea方法形参赋值时的变量提示
    更换Android studio中的SDK和AVD位置
    CSS/CSS3 | P4-选择器优先级权重
    二叉树的性质
    线性表练习
    前插法建立链表
    格式化文件和数据块读写函数
  • 原文地址:https://www.cnblogs.com/msj513/p/9806465.html
Copyright © 2020-2023  润新知