【Python】configparser - 配置文件解析

 

目录

一. 介绍 

二. 说明

三. 示例

四. 参考


 

一. 介绍 

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

 

 

(完)

 

 

你可能感兴趣的:(Python,python)