configparser模塊

configparser模塊可用來對制定配置文件進行增刪改查spa

1.新建一個配置文件3d

 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)

生成的配置文件:code

2.讀配置文件server

 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)

運行結果:blog

3.修改節點rem

 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'))

運行結果:it

相關文章
相關標籤/搜索