1. 程式人生 > 其它 >【Python】configparser - 配置檔案解析

【Python】configparser - 配置檔案解析

技術標籤:Pythonpython

目錄

一. 介紹

二. 說明

三. 示例

四. 參考


一. 介紹

ConfigParse 類實現一個基本配置檔案解析器語言,提供了一個類似於Microsoft Windows INI 檔案的結構。

可以使用它來編寫可由終端使用者輕鬆定製的Python程式。

注意:這個庫不支援能夠解析或寫入在 Windows Registry 擴充套件版本 INI 語法中所使用的值-型別字首。

二. 說明

配置檔案由組成,節由[section]標題和後面的條目開頭,並以樣式繼續。樣式請參考RFC 822文件;

即如下形式:

# 節
[SELECTION_ONE]
a = 1
one = 1

# 節
[SELECTION_TWO]
b = 2
two = 2

# 節
[set_section]
set_option = set_value # option:value

配置檔案中可能包含註釋,並以特定字元(#;)為字首。

類定義:

class ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

三. 示例

# -*- coding:utf-8 -*-

import configparser

file_name = 'conf/configParse.conf'


def writeConfig():
    'the write config'
    config = configparser.ConfigParser()
    config["DEFAULT"] = {'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D'}
    config['SELECTION_ONE'] = {'A': 1, 'one': '1'}
    config['SELECTION_TWO'] = {'B': 2, 'two': 2}
    with open(file_name, 'w') as file:
        config.write(file)


def readConfig():
    'the read config'
    config = configparser.ConfigParser()
    config.read(file_name)
    print(config.sections())
    # print(config.options('SELECTION_ONE'))
    # print(config.options('SELECTION_TWO'))
    #
    # print(config.items('SELECTION_ONE'))
    # print (config.items('SELECTION_TWO'))
    #
    # print(config.get('SELECTION_ONE', 'ONE'))
    # print(config.get('SELECTION_TWO', 'TWO'))


def repairedConfig():
    'the repaired config'
    config = configparser.ConfigParser()
    config.read(file_name)
    print(config.sections())
    config.add_section('add_section')
    config.remove_section('add_section')

    if 'set_section' not in config:
        config.add_section('set_section')

    config.set('set_section', 'set_option', 'set_value')
    config.set('set_section', 'DovSnieir', '資深好男人')
    print(config.sections())
    with open(file_name, 'w') as file:
        config.write(file)


if __name__ == "__main__":
    '''主函式入口'''
    # 寫
    writeConfig()
    # 修
    repairedConfig()
    # 讀
    readConfig()

四. 參考

  1. https://docs.python.org/zh-cn/2.7/library/configparser.html
  2. https://docs.python.org/zh-cn/2.7/library/configparser.html#configparser-objects
  3. https://docs.python.org/zh-cn/2.7/library/configparser.html#examples
  4. https://tools.ietf.org/html/rfc822.html

(完)