日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

【python】詳解使用configparser進行文件配置

系統 2634 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條評論
主站蜘蛛池模板: 滨州市| 枣强县| 株洲市| 龙南县| 镇原县| 信宜市| 陵川县| 三穗县| 白玉县| 安化县| 鸡东县| 旺苍县| 仪陇县| 郯城县| 尼勒克县| 罗甸县| 阳原县| 安多县| 呼伦贝尔市| 洛浦县| 静乐县| 靖安县| 克拉玛依市| 卢湾区| 玉溪市| 雷州市| 阿城市| 台山市| 芜湖县| 遂平县| 灌阳县| 德令哈市| 当阳市| 阳新县| 临泽县| 南陵县| 鲜城| 忻城县| 博爱县| 宣化县| 定南县|