ConfigParser模块

一、ConfigParser的作用

  用于生成和修改常见的配置文件用;

二、ConfigParser写配置文件

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

生成结果:

 1 [DEFAULT]
 2 compression = yes
 3 serveraliveinterval = 45
 4 compressionlevel = 9
 5 forwardx11 = yes
 6 
 7 [bitbucket.org]
 8 user = hg
 9 
10 [topsecret.server.com]
11 host port = 50022
12 forwardx11 = no

三、ConfigParser读文件

1 #读文件内容
2 import configparser
3 config=configparser.ConfigParser()
4 
5 config.read("example.ini")
6 #sections只读取非DEFALUT部分
7 print(config.sections())
8 print(config['bitbucket.org']['user'])

 

posted @ 2016-12-23 11:16  dudujing  阅读(32)  评论(0)    收藏  举报