zoukankan      html  css  js  c++  java
  • python configparser模块

    一、configparser介绍

     configparser模块主要用于读取配置文件(*.ini),导入方法:from configparser import ConfigParser

    二、configparser初始化

    目录结构:

    api_test

    - common

    - config

      -apiConfig.ini 配置文件所在目录

      -readConfig.py 读取配置文件(代码在此写入)

    import os
    from configparser import ConfigParser
    
    config = ConfigParser()
    #获取当前目录配置文件 config_path
    = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'apiConfig.ini') # print(config_path) config.read(config_path,encoding='utf-8')

     三、基本操作

    配置文件:apiConfig.ini 

    [host]
    host = 127.0.0.1:12306
    MobileCodeWS_host = ws.webxml.com.cn
    WeatherWebService_host = www.webxml.com.cn
    
    [header]
    header1 = {"Content-Type": "application/json"}
    header2 = {"Content-Type": "application/json;charset=UTF-8"}
    header3 = {"Content-Type": "application/json", "description": "$RandomString(10)$",
                "timestamp": "$GetTime(time_type=now,layout=13timestamp,unit=0,0,0,0,0)$", "sign": "$SHA1(${description}$, ${timestamp}$)$"}
    
    [MySqlDB]
    host = localhost
    port = 3306
    user = root
    pwd = root
    db = course
    charset = utf8
    

    1. 获取节点sections

    ConfigParserObject.sections()
    以列表形式返回configparser对象的所有节点信息

    #获取所有节点
    all_sections = config.sections()
    print("sections: ",all_sections)#sections:  ['host', 'header', 'MySqlDB']

    2. 获取指定节点的所有配置信息

    ConfigParserObject.items(section)
    以列表形式返回某个节点section对应的所有配置信息

    #获取指定节点到配置信息
    items = config.items('host')
    print(items)#[('host', '127.0.0.1:12306'), ('mobilecodews_host', 'ws.webxml.com.cn'), ('weatherwebservice_host', 'www.webxml.com.cn')]

    3. 获取指定节点的options

    ConfigParserObject.options(section)
    以列表形式返回某个节点section的所有key值

    #获取指定节点的options
    options = config.options('host')
    print(options)#['host', 'mobilecodews_host', 'weatherwebservice_host']

    4. 获取指定节点下指定option值

    • ConfigParserObject.get(section, option)
      返回结果是字符串类型
    • ConfigParserObject.getint(section, option)
      返回结果是int类型
    • ConfigParserObject.getboolean(section, option)
      返回结果是bool类型
    • ConfigParserObject.getfloat(section, option)
      返回结果是float类型
    #获取指定节点指定option的值
    host = config.get('host','host')
    print(host,type(host))#127.0.0.1:12306 <class 'str'>
    
    port = config.getint('MySqlDB','port')
    print(port,type(port))#3306 <class 'int'>

    5.检查section或option是否存在

    • ConfigParserObject.has_section(section)
    • ConfigParserObject.has_option(section, option)
      返回bool值,若存在返回True,不存在返回False
    #检查section是否存在
    has_section1 = config.has_section('host')
    print(has_section1) #结果True
    has_section2 = config.has_section('hostt')
    print(has_section2) #结果False
    #检查option是否存在
    has_option1 = config.has_option('host','host')
    print(has_option1) #结果True
    has_option2 = config.has_option('host','localhost')
    print(has_option2) #结果False

    6. 添加section

    ConfigParserObject.add_section(section)
    如果section不存在,则添加节点section;
    若section已存在,再执行add操作会报错configparser.DuplicateSectionError: Section XX already exists

    #添加section
    if not config.has_section('ohters'):
        config.add_section('others')
    config.set('others','hello','world')
    with open(config_path,'w+') as f:
        config.write(f)
    others = config.items('others')
    print(others) #结果[('hello', 'world')]

    7. 修改或添加指定节点下指定option的值

    ConfigParserObject.set(section, option, value)
    若option存在,则会替换之前option的值为value;
    若option不存在,则会创建optiion并赋值为value
    #修改指定option的值
    config.set('host','host','www.baidu.com') #存在,替换host地址
    config.set('host','test','test') #不存在,创建option并赋值
    config.write(open(config_path,'w+'))
    #重新查看修改后节点信息
    items = config.items('host')
    print("修改后的items",items)
    #结果修改后的items [('host', 'www.baidu.com'), ('mobilecodews_host', 'ws.webxml.com.cn'), ('weatherwebservice_host', 'www.webxml.com.cn'), ('test', 'test')]

    8. 删除section或option

    • ConfigParserObject.remove_section(section)
      若section存在,执行删除操作;
      若section不存在,则不会执行任何操作
    • ConfigParserObject.remove_option(section, option)
      若option存在,执行删除操作;
      若option不存在,则不会执行任何操作;
      若section不存在,则会报错configparser.NoSectionError: No section: XXX
    #删除section
    config.remove_section('others') #section存在
    config.remove_section('no_others') #section不存在
    
    #删除option
    config.remove_option('host','test')#option存在
    config.remove_option('host','no_option') #option不存在
    config.write(open(config_path,'w+'))

    9. 写入内容

    ConfigParserObject.write(open(filename, 'w'))
    对configparser对象执行的一些修改操作,必须重新写回到文件才可生效

    config.write(open(filename, 'w'))
    or
    with open(self.conf_path, "w+") as f:
        return self.config.write(f)
    
    
  • 相关阅读:
    DTOJ #3328. 开箱子(unboxing)
    dtoi4649 光明
    dtoi4539「TJOI / HEOI2016」序列
    dtoi3031 交错和查询 (sum)
    dtoi4375「BJOI2019」删数
    dtoi4266 exchange
    dtoi4680 红黑兔
    dtoi1363 楼房重建 (rebuild)
    dtoi1927 [ONTAK2010]Peaks加强版
    dtoi4538 「TJOI / HEOI2016」排序
  • 原文地址:https://www.cnblogs.com/helloTerry1987/p/12732231.html
Copyright © 2011-2022 走看看