configparser模块:用于生成和修改常见配置文档
来看一下开源软件的常见文档格式如下
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
用python生成一个这样的文档
#!/usr/bin/env python
# coding: utf-8
__author__ = 'www.py3study.com'
import configparser
#创建一个ConfigParser对象
config = configparser.ConfigParser()
#默认参数
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
#添加一个节点bitbucket.org
config['bitbucket.org'] = {}
#增加节点的属性值
config['bitbucket.org']['User'] = 'hg'
#添加一个节点topsecret.server.com
config['topsecret.server.com'] = {}
#将节点赋值给topsecret
topsecret = config['topsecret.server.com']
#添加属性
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
#给DEFAULT添加属性
config['DEFAULT']['ForwardX11'] = 'yes'
#写入配置文件example.ini
with open('example.ini', 'w') as configfile:
config.write(configfile)
执行程序,查看example.ini文件内容
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no
读取文件内容
1、获取所有节点
import configparser
config = configparser.ConfigParser()
config.read('example.ini', encoding='utf-8')
ret = config.sections()
print(ret)
执行输出
['bitbucket.org', 'topsecret.server.com']
sections()不会返回default的值,如果需要,使用defaults()方法
print(config.defaults())
执行输出
OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
2、获取指定节点下指定key的值
import configparser
config = configparser.ConfigParser()
config.read('example.ini', encoding='utf-8')
ret = config['bitbucket.org']['user']
print(ret)
执行输出 hg
或者
ret = config.get('bitbucket.org','user')
执行输出 效果同上
删除一个节点
#删除一个节点
ret = config.remove_section('bitbucket.org')
#写入到新文件i.cfg
config.write(open('i.cfg', "w"))
查看i.cfg文件内容
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[topsecret.server.com]
host port = 50022
forwardx11 = no
判断节点是否存在
sec = config.has_section('wupeiqi')
print(sec)
执行输出 False
添加一个节点
sec = config.add_section('wupeiqi')
config.write(open('i.cfg', "w"))
执行程序,查看文件内容
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no
[wupeiqi]
删除一个属性
sec = config.remove_option('topsecret.server.com','forwardx11')
config.write(open('i.cfg', "w"))
执行程序,查看文件内容
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022