zoukankan      html  css  js  c++  java
  • python模块----configpaser (key:value型 配置文件解析器)

    configparser是用来读取配置文件的包,配置文件的格式类似:[section]+内容(键=值)

    示例:

    [db]
    db_host = 127.0.0.1
    db_port = 69
    db_user = root
    db_pass = root
    host_port = 69
    

    使用方法

    第一步:导入模块并初始化

    import configparser
    config= configparser.ConfigParser()
    config.read('file_path',encoding="utf-8")
    

    第二部:常用方法

    获取所有section节点

    print(config.sections())
    

    获取指定section的options(即:键=值中的键)

    r=config.options('db')
    print(r)
    

    获取指定section指定option的值

    r=config.get('db','db_host')
    # r1 = config.getint("db", "k1") #将获取到值转换为int型
    # r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型
    # r3 = config.getfloat("db", "k3" ) #将获取到值转换为float型
    print(r)
    

    获取指定section的所有配置信息

    r=config.items('db')
    print(r)
    

    查看section或option是否存在

    config.has_section("section") #是否存在该section
    config.has_option("section", "option")  #是否存在该option
    

    修改指定section指定option的值(如果不存在该option会新创建)

    config.set('db','db_host','127.0.0.2')
    config.write(open('file_path','w')) #如果没有这一步源文件内容不改变
    

    添加section和option

    if not config.has_section('addsection')
        config.add_section('addsection')
    if not config.has_option('section','addoption')
        config.set('section','addoption','value')
    config.write(open('file_path','w'))
    

    删除section和option

    config.remove_section('section') #删除整个section所有内容
    
    
  • 相关阅读:
    python 元类
    python中__init__()、__new__()、__call__()、__del__()用法
    python内置数据结构方法的时间复杂度
    时间复杂度和空间复杂度
    数据结构及算法(1)
    sys模块python
    python中的文本操作
    python 中的os模块
    python 几种不同的格式化输出
    【js】null 和 undefined的区别?
  • 原文地址:https://www.cnblogs.com/du-z/p/12838630.html
Copyright © 2011-2022 走看看