configparser模块可用来对制定配置文件进行增删改查

1.新建一个配置文件

 1 import configparser
 2 
 3 config=configparser.ConfigParser()
 4 
 5 config['DEFAULT']={
 6     'ServerAlinveInterval':'34',
 7     'Compression':'yes',
 8     'CompressionLevel':'6'
 9 }
10 
11 config['bitbucket.org']={}
12 config['bitbucket.org']['User']='hg'
13 
14 config['topsecret.server.com']={}
15 config['topsecret.server.com']['Host Port']='23121'
16 config['topsecret.server.com']['ForwardX11']='no'
17 
18 config['DEFAULT']['ForwardX11']='yes'
19 
20 with open('setupconf.ini','w') as configfile:
21     config.write(configfile)

生成的配置文件:

2.读配置文件

 1 import configparser
 2 
 3 config=configparser.ConfigParser()
 4 config.read('setupconf.ini')
 5 print(config.sections())#只打印节点
 6 
 7 print(config.defaults())#打印defaults下内容
 8 
 9 print(config['bitbucket.org']['User'])#与字典类似
10 
11 #循环节点打印
12 for key in config['bitbucket.org']:
13     print(key)

运行结果:

3.修改节点

 1 import configparser
 2 
 3 config=configparser.ConfigParser()
 4 config.read('setupconf.ini')
 5 
 6 config.remove_section('bitbucket.org')#删除bitbucket.org
 7 
 8 print(config.has_section('ABCDEFG.com'))#判断是否有该节点返回True或False
 9 
10 config.add_section('ABCDEFG.com')#新增一个节点
11 
12 config.set('topsecret.server.com','host port','123123')#更改topsecret.server.com下的host port参数
13 
14 config.write(open('modifyconfig.cfg','w'))

运行结果:

posted on 2018-10-30 22:20  研究僧桃子  阅读(86)  评论(0编辑  收藏  举报