python模块之configparser

此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

解析下面的文件格式:

[DEFAULT]
ServerAliveInterval = 45   
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

解析配置文件

import configparser

conf = configparser.ConfigParser()  # 实例化(生成对象)

# print(conf.sections()) #调用sections方法  []

conf.read('conf.ini')  # 读配置文件(注意文件路径)

print(conf.sections())  # 调用sections方法(默认不会读取default  #['bitbucket.org', 'topsecret.server.com']
print(conf.default_section)  # ['bitbucket.org', 'topsecret.server.com']

# print(conf['bitbucket.org']['User']) # hg

for key, value in conf['bitbucket.org'].items():
    print(key, value)  # 每个节点会有默认有DEFAULT的参数
'''
user hg
serveraliveinterval 45
compression yes
compressionlevel 9
forwardx11 yes
'''

if 'user' in conf['bitbucket.org']:
    print('True')

增删改查
#

conf = configparser.ConfigParser()

conf.read('conf2.ini')
#
print(conf.options('group1'))  # 拿到key
print(conf['group1']['k2'])  # v2 拿到value

print(conf.has_option('group1', 'key1'))  # False

#

conf.add_section('group3')
conf['group3']['name'] = 'Alex Li'
conf['group3']['age'] = '22'
conf.write(open('conf3.ini', 'w'))

'''
[group1]
k1 = v1
k2 = v2

[group2]
k1 = v1

[group3]
name = Alex Li
age = 22
'''

#


conf.remove_option('group1', 'k2')
conf.remove_section('group1')  # 把整个group1和里面的内容全删了
conf.write(open('conf4.ini', 'w'))

#

conf['group1']['k1'] = 'haha'
conf.write(open('conf2.ini', 'w'))
给Default增加值的话直接加,不用sections,用sections会报错,sections不会读取default 
conf['DEFAULT']['character-set-server'] = 'utf-8'
conf.write(open('co f2.ini', 'w'))

原文地址:https://www.cnblogs.com/lshedward/p/10005708.html