【python】详解使用configparser进行文件配置

系统 1654 0

        将代码中的配置项抽取到配置文件中,修改配置时不需要涉及到代码修改,这样就提高了代码的重用性,不再每次都去修改代码内部,极大的方便后期软件的维护。
        configparser解析的配置文件的格式为ini的配置文件格式 (xxx.ini) ,就是文件中由多个section构成,每个section下又有多个配置项:

            
              ;配置文件
#  定义section0
[section0]
 
key0 = value0
key1 = value1
 
[section1]
 
key2 = value2
key3 = value3

            
          

      1. 配置文件实例样本

        section不能重复,里面数据通过section去查找,每个seletion下可以有多个key和vlaue的键值对,注释用英文分号【;】

            
              ;定义config分组
[config]
platformName=BBB
ip=100.100
port=193

;定义editor分组
[editor]
author=bruce
job=fun
id=five

;定义log分组
[log]
log_error=true

            
          

      2. 通过configparser进行操作

configparser是Python自带的模块,用法如下:

  • 1.创建ConfigParser对象。并调用read()函数打开配置文件,里面填的参数是地址

  • 2.配置文件的格式是:[]包含的叫section,section下有option=value这样的键值

  • 3.常用配置函数如下

    • sections() 得到所有的section,并以列表的形式返回
    • options(section) 得到该section的所有option (key值)
    • items(section) 得到该section的所有键值对,返回结果是列表中包含的元祖
    • get(section, option) 得到section中option的值,返回为string类型,指定标签下面的key对应的value值
    • getint(section, option) 得到section中的option值,返回为int类型
    • has_section(section) 判断指定的option是否存在
    • has_option(section,option)判断指定option中的option是否存在
    • add_section(str) 往配置文件中添加section
    • set(section, name, value) 在section下设置name=value
    • remove_option(section,option)删除指定节点section中的option
    • remove_section(section)删除指定的section
    • read(filename) 读取配置文件, read(’./config.ini’)
    • write(obj_file) 写入配置文件 ,write(open(“config.ini”, “w”))

      3. 详解configparser操作

            
              import configparser


class Operation(object):

    def __init__(self, cf):
        self.cf = cf

    def get_sections(self):
        print('------------------------ ----- ---------------------------')
        # 得到所有的section,并以列表的形式返回
        print('Current function is get_sections, the answer is:', self.cf.sections())
        return

    def get_options(self, option_name):
        print('------------------------ ----- ---------------------------')
        # 得到该section的所有option (key值)
        print('Current function is get_options, the answer is:', self.cf.options(option_name))
        return

    def get_items(self, option_name):
        print('------------------------ ----- ---------------------------')
        # 得到该section的所有键值对
        print('Current function is get_items, the answer is:', self.cf.items(option_name))
        return

    def get_editor_value(self, option_name, key_name):
        print('------------------------ ----- ---------------------------')
        # 得到section中option的值,返回为string类型,指定标签下面的key对应的value值
        print("Current function[get] is get_editor_value, the answer from {}'s {} is: {}".format(option_name, key_name,
                                                                                                 self.cf.get(option_name,
                                                                                                             key_name)))
        return

    def get_editor_int_value(self, option_name, key_name):
        print('------------------------ ----- ---------------------------')
        # 得到section中的option值,返回为int类型
        print("Current function[get] is get_editor_value, the answer from {}'s {} is: {}".format(option_name, key_name,
                                                                                                 self.cf.get(option_name,
                                                                                                             key_name)))

        return

    def has_section(self, section_name):
        # 判定是否存在某section
        print('------------------------ ----- ---------------------------')
        print('has {} sections:{}'.format(section_name, self.cf.has_section(section_name)))

    def has_option(self, section_name, option_name):
        # 判定是否存在某section
        print('------------------------ ----- ---------------------------')
        print("has {}'s {} value:{}".format(section_name, option_name, self.cf.has_option(section_name, option_name)))

    def set_add_function(self, section_name):
        # 添加一个节点section_name,但此时尚未写入文件
        print('------------------------ ----- ---------------------------')
        print('former sections:', self.cf.sections())
        self.cf.add_section(section_name)
        print('later sections:', self.cf.sections())
        return

    def set_section_value(self, section_name, option_name, key_name):
        print('------------------------ ----- ---------------------------')
        # 在已存在的节点中添加一个键值对k1 = v1 ,如果该节点不存在则报错,如果key已经存在,则修改value
        self.cf.set(section_name, option_name, key_name)
        self.cf.write(open("config.ini", "w"))             # 将添加的option写入配置文件
        return

    def remove_option(self, section_name, option_name):
        print('------------------------ ----- ---------------------------')
        # 删除section中的option值
        self.cf.remove_option(section_name, option_name)   # 删除section中的option值
        self.cf.write(open("config.ini", "w"))             # 将添加的option写入配置文件
        return

    def remove_section(self, section_name):
        print('------------------------ ----- ---------------------------')
        # 删除section
        self.cf.remove_section(section_name)               # 删除section
        self.cf.write(open("config.ini", "w"))             # 将添加的option写入配置文件
        return


if __name__ == '__main__':
    cf = configparser.ConfigParser()
    cf.read('./config.ini')
    ops = Operation(cf)
    ops.get_sections()
    ops.get_options('editor')
    ops.get_items('editor')
    ops.get_editor_value('editor', 'job')
    ops.get_editor_int_value('editor', 'id')
    ops.has_section('editor')
    ops.has_option('editor', 'id')
    ops.set_add_function('new_section')
    ops.set_section_value('new_section', 'set', 'new_value')
    print("current new_section is :", ops.cf.items('new_section'))
    ops.remove_option('new_section', 'set')
    ops.remove_section('new_section')


            
          

结果

            
              ------------------------ ----- ---------------------------
Current function is get_sections, the answer is: ['config', 'editor', 'log']
------------------------ ----- ---------------------------
Current function is get_options, the answer is: ['author', 'job', 'id']
------------------------ ----- ---------------------------
Current function is get_items, the answer is: [('author', 'bruce'), ('job', 'fun'), ('id', '5')]
------------------------ ----- ---------------------------
Current function[get] is get_editor_value, the answer from editor's job is: fun
------------------------ ----- ---------------------------
Current function[get] is get_editor_value, the answer from editor's id is: 5
------------------------ ----- ---------------------------
has editor sections:True
------------------------ ----- ---------------------------
has editor's id value:True
------------------------ ----- ---------------------------
former sections: ['config', 'editor', 'log']
later sections: ['config', 'editor', 'log', 'new_section']
------------------------ ----- ---------------------------
current new_section is : [('set', 'new_value')]
------------------------ ----- ---------------------------
------------------------ ----- ---------------------------

            
          

更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论