ConfigParser模块

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

来看一个好多软件的常见文档格式如下

 1 [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6  
 7 [bitbucket.org]
 8 User = hg
 9  
10 [topsecret.server.com]
11 Port = 50022
12 ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

 1 import configparser
 2 
 3 config=configparser.ConfigParser()  #文件配置句柄
 4 
 5 config["DEFAULT"] = {'ServerAliveInterval': '45',
 6                      'Compression': 'yes',
 7                      'CompressionLevel': '9'} #
 8 
 9 config['bitbucket.org'] = {}
10 config['bitbucket.org']['User'] = 'hg'
11 config['topsecret.server.com'] = {}
12 topsecret = config['topsecret.server.com']
13 topsecret['Host Port'] = '50022'  # mutates the parser
14 topsecret['ForwardX11'] = 'no'  # same here
15 config['DEFAULT']['ForwardX11'] = 'yes'
16 with open('example.ini', 'w') as configfile:
17     config.write(configfile)

结果:

查看::

 1 import configparser
 2 
 3 config=configparser.ConfigParser()
 4 
 5 
 6 
 7 config.read('example.ini')
 8 print(config.sections())
 9 
10 
11 print('bitbucket.org' in config)
12 
13 print(config.defaults())
14 
15 print(config['bitbucket.org']['User'])
16 print(config['topsecret.server.com']['ForwardX11'])
17 print('------               -------')
18 for key in config['bitbucket.org']:
19     print(key)

运行结果:

 

 

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 #---------------------------------------------查
 6 print(config.sections())   #[]
 7 
 8 config.read('example.ini')
 9 
10 print(config.sections())   #['bitbucket.org', 'topsecret.server.com']
11 
12 print('bytebong.com' in config)# False
13 
14 print(config['bitbucket.org']['User']) # hg
15 
16 print(config['DEFAULT']['Compression']) #yes
17 
18 print(config['topsecret.server.com']['ForwardX11'])  #no
19 
20 
21 for key in config['bitbucket.org']:
22     print(key)
23 
24 
25 # user
26 # serveraliveinterval
27 # compression
28 # compressionlevel
29 # forwardx11
30 
31 
32 print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
33 print(config.items('bitbucket.org'))  #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
34 
35 print(config.get('bitbucket.org','compression'))#yes
36 
37 
38 #---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
39 
40 
41 config.add_section('yuan')
42 
43 config.remove_section('topsecret.server.com')
44 config.remove_option('bitbucket.org','user')
45 
46 config.set('bitbucket.org','k1','11111')
47 
48 config.write(open('i.cfg', "w"))
49 
50 增删改查
插卡,修改,增删。。

 

posted @ 2018-07-05 13:29  巨兽~墨菲特  阅读(94)  评论(0编辑  收藏  举报