python配置文件解析_【Python】configparser - 配置文件解析

目录

一. 介绍

ConfigParse 类实现一个基本配置文件解析器语言,提供了一个类似于Microsoft Windows INI 文件的结构。

可以使用它来编写可由最终用户轻松定制的Python程序。

注意:这个库不支持能够解析或写入在 Windows Registry 扩展版本 INI 语法中所使用的值-类型前缀。

二. 说明

配置文件由节组成,节由[section]标题和后面的条目开头,并以样式继续。样式请参考

即如下形式:

# 节

[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()

四. 参考

(完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值