python ConfigParser 模块简介

常用模块configparser

一、导入模块与创建对象

import configparser
config = configparser.ConfigParser()

二、读取配置文件

config.read('config.ini', encoding='utf-8')

三、获取节点section下的数据,返回字典

    if config.has_section(section):
        dict_res = dict(config.items(section))

四、常用方法介绍

名称描述
ConfigParser()创建configparser对象
sections()返回配置文件的所有section名字,除了DEFAULT。
has_section(section)返回一个布尔值,判断配置文件中是否有该section。
options(section)返回配置文件中指定的section下option的一个列表;除了指定的section在内外,还会自动加上 DEFAULT下的option;
has_option(section, option)返回一个布尔值,判断配置文件中是否有指定section下的option。
read(filenames, encoding=None)读取配置文件的内容到对象
read_file(f, filename=None)读取配置文件的内容到对象;这里的f是一个文件的句柄
f=open('example.ini')
config.read_file(f)
# 这两句等效config.read('example.ini')
read_string(string)从指定的字符串中读取配置到对象
read_dict(dictionary)从指定的字典读取配置到对象;字典的key为section的名字,value为字典形式,即option和值;
get(section, option, raw=False, vars=None, fallback=_UNSET)返回指定section、option对应的值;vars是字典类型,如果指定了vars,option 的查找顺序为 vars、section 以及 DEFAULTSECT。 如果未找到该键并且提供了 fallback,则它会被用作默认值返回。 
getint(section, options, raw=False, vars=None, fallback=_UNSET)类似get方法,但是将值转换为一个整数
getfloat(section, options, raw=False, vars=None, fallback=_UNSET)类似get方法,但是将值转换为一个浮点数
getboolean(section, options, raw=False, vars=None, fallback=_UNSET)类似get方法,但是将值转换为一个布尔值;
当前是 0, false, no, off 的都会转换为 False;当前值是 1, true, yes, on 的都会转换为 True.
items(section=_UNSET, raw=False, vars=None)如果指定了section,则返回指定section的option和值;同时也附带DEFAULT下面option和值;返回的是一个列表嵌套元组的形式,建议指定section,不指定section返回的是可迭代对象
remove_section(section)删除指定的section及它下面的所有options
remove_option(section, option)删除指定的section的option
set(section, option, value)添加/设置指定的section下option
write(f, space_around_delimiters=True)space_around_delimiters为True时,键和值之前的分隔符两边将加上空格。
将对象写入指定的文件中
with open("test.ini", "w+") as f:
    cf.write(f)
add_section(section)添加一个新的section

五、示例

创建、读取、新增与删除节点和选项、修改选项数据

import configparser

def create_inidata(inifile='config_test.ini'):
    config = configparser.ConfigParser()

    #不调用方法生成节点section数据
    config["dirname"] = {}
    config["filerule"] = {"checkdata": "checkdata:gd"}
    config["filemode"] = {"isenable": "True", "mode": "update"}
    config["wlan"] = {"isenable": "False"}

    with open(inifile, 'w+') as configfile:
        config.write(configfile)
    if config:
        for i in config:
            print('config data:', i)


def conf_mathod(inifile='config_test.ini'):
    config = configparser.ConfigParser()
    config.read(inifile, encoding='utf-8')
    #配置文件数据读取
    print(config['filemode'])
    print(config['filemode']['mode'])
    print('sections:', config.sections())
    print('options:', config.options('filemode'))
    print('get mode:', config.get('filemode', 'mode'))
    print('filemode items:', config.items('filemode'))
    print('items dict:', dict(config.items('filemode')))

    # 配置文件节点section和选项option新增
    if not config.has_section('TestAddSection'):
        config.add_section('TestAddSection')
        config.set('TestAddSection', 'aoption', 'a')
        config.set('TestAddSection', 'boption', 'b')

    #配置文件节点section和选项option删除
    if config.has_section('TestAddSection'):
        # remove_option
        if config.has_option('TestAddSection', 'boption'):
            config.remove_option('TestAddSection', 'boption')
        print('After Remove A Option,Items:', config.items('TestAddSection'))
        config.remove_section('TestAddSection')

        if not config.has_section('TestAddSection'):
            print('Section TestAddSection is removed!')

    # 删除后再新增
    if not config.has_section('TestAddSection'):
        config.add_section('TestAddSection')
        config.set('TestAddSection', 'aoption', 'a')
        config.set('TestAddSection', 'boption', 'b')
        #读取字典数据生成配置文件数据
        dict_data = {'TestAddSection': {'coption': 'c'}}
        config.read_dict(dict_data)

    if config.has_section('TestAddSection'):
        print('config.items:', config.items('TestAddSection'))
        if config.has_option('TestAddSection', 'boption'):
            #修改选项option数据
            config.set('TestAddSection', 'boption', 'b changed!')

            #get用法
            #get(section, option, raw=False, vars=None, fallback=_UNSET)
            #如果指定了vars,option 的查找顺序为 vars、section 以及 DEFAULTSECT。
            res = config.get('TestAddSection', 'boption', raw=False, vars={'baz': 'evil', 'boption': 'from vars'}, fallback='defaultvalue')
            print(f"get用法:raw=False,vars存在,使用vars中的值进行匹配:{res}")

            res = config.get('TestAddSection', 'boption', raw=True, vars={'baz': 'evil', 'boption': 'from vars'}, fallback='defaultvalue')
            print(f"get用法:raw=True,vars存在,使用vars中的值进行匹配:{res}")

            res = config.get('TestAddSection', 'boption', raw=False, vars={'baz': 'evil'}, fallback='defaultvalue')
            print(f"get用法:raw=False,vars存在,但vars无boption, 返回ini文件boption匹配值:{res}")

            res = config.get('TestAddSection', 'boption2', raw=False, fallback='defaultvalue')
            print(f"get用法:未匹配成功,返回默认值:{res}")

    with open(inifile, 'w+') as configfile:
        config.write(configfile)


if __name__ == '__main__':
    ini_file = 'config_test.ini'
    create_inidata(ini_file)
    conf_mathod(ini_file)

执行后配置文件:

[dirname]

[filerule]
checkdata = checkdata:gd

[filemode]
isenable = True
mode = update

[wlan]
isenable = False

[TestAddSection]
aoption = a
boption = b changed!
coption = c

打印结果:

config data: DEFAULT
config data: dirname
config data: filerule
config data: filemode
config data: wlan
<Section: filemode>
update
sections: ['dirname', 'filerule', 'filemode', 'wlan']
options: ['isenable', 'mode']
get mode: update
filemode items: [('isenable', 'True'), ('mode', 'update')]
items dict: {'isenable': 'True', 'mode': 'update'}
After Remove A Option,Items: [('aoption', 'a')]
Section TestAddSection is removed!
config.items: [('aoption', 'a'), ('boption', 'b'), ('coption', 'c')]
get用法:raw=False,vars存在,使用vars中的值进行匹配:from vars
get用法:raw=True,vars存在,使用vars中的值进行匹配:from vars
get用法:raw=False,vars存在,但vars无boption, 返回ini文件boption匹配值:b changed!
get用法:未匹配成功,返回默认值:defaultvalue

六、定义一个可复用的方法

代码示例:

import configparser

def get_inidata(inifile='config.ini', section=None):
    config = configparser.ConfigParser()
    config.read(inifile, encoding='utf-8')
    if config.has_section(section):
        return dict(config.items(section))
    return {}


if __name__ == '__main__':
    ini_file = 'config_test.ini'
    print(get_inidata(ini_file, section='TestAddSection'))

结果:

{'aoption': 'a', 'boption': 'b changed!', 'coption': 'c'}

七、官网中文版文档说明

官网中文版文档说明:

configparser --- 配置文件解析器 — Python 3.11.8 文档

https://docs.python.org/zh-cn/3.11/library/configparser.html#configparser.ConfigParser

  • 26
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值