configparser模块——配置文档

configparser模块用于生成和修改常见配置文档。

预制配置文件:conf.ini

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

[bitbucket.org]
User = hg
MaxUsers = 100

[topsercret.server.com]
Port = 50022
ForwardX11 = no
解析配置文件
>>> import configparser
>>> conf = configparser.ConfigParser()  # 准备处理文件
>>> conf.read('conf_ini')
['conf_ini']
>>> print(conf.sections())
['bitbucket.org', 'topsercret.server.com']
>>> print(conf.default_section)
DEFAULT
>>> 'bitbucket.org' in conf
True
>>> conf['bitbucket.org']['User']
'hg'
>>> print(list(conf['bitbucket.org'].keys()))
['user', 'maxusers', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
>>> for k in conf['topsercret.server.com']:
...     print(k)   
... 
port
forwardx11
serveraliveinterval
compression
compressionlevel

  可以发现,每个节点都会默认包含default值。

增删改查

首先准备conf_test.ini文件

[group1]
k1 = v1
k2:v2

[group2]
k1=v1

对conf_test_ini文件进行读和添加操作:

>>> import shutil
>>> shutil.copyfile('conf_ini', 'conf_test.ini')
'conf_test.ini'
# vim conf_test.ini  修改配置文件信息

>>> import ConfigParser
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'ConfigParser'
>>> import configparser
>>> conf = configparser.ConfigParser()
>>> conf.read('conf_test.ini')
['conf_test.ini']
print(dir(conf))
['BOOLEAN_STATES', 'NONSPACECRE', 'OPTCRE', 'OPTCRE_NV', 'SECTCRE', '_DEFAULT_INTERPOLATION',...'set', 'setdefault', 'update', 'values', 'write']
>>> print(conf.options('group1'))
['k1', 'k2']
>>> print(conf['group1']['k2'])
v2
>>> conf.add_section('group3')
>>> conf['group3']['name'] = 'hqs'
>>> conf['group3']['age'] = '22'   # 不能使用数字
>>> conf.write(open('conf_test.ini', 'w'))  # 写入新文件
[group1]
k1 = v1
k2 = v2

[group2]
k1 = v1

[group3]
name = hqs
age = 22

对conf_test_ini文件进行删操作

>>> import configparser
>>> conf = configparser.ConfigParser()
>>> conf.read('conf_test.ini')
['conf_test.ini']
>>> conf.remove_option('group1', 'k2')   # 删除某一项
True
>>> conf.write(open('conf_test.ini', 'w'))

[group1]
k1 = v1

[group2]
k1 = v1

[group3]
name = hqs
age = 22
>>> import configparser
>>> conf = configparser.ConfigParser()
>>> conf.read('conf_test.ini')
['conf_test.ini']
>>> conf.remove_section('group3')    # 删除某一整个章节
True
>>> conf.write(open('conf_test.ini', 'w'))
>>> ^D
MacBook-Pro:Desktop hqs$ cat conf_test.ini 
[group1]
k1 = v1

[group2]
k1 = v1

 

posted @ 2018-04-05 00:49  休耕  阅读(487)  评论(0编辑  收藏  举报