config:配置,parser:解析。字面意思理解configparser模块就是配置文件的解析模块。

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

[DEFAULT]                              # 标题性的东西,
# 下面四组键值对是关于[DEFAULT]的介绍
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no
  • 用Python生成配置文件

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

import configparser

config = configparser.ConfigParser()   # 实例出来一个对象,相当于创建了一个空字典config={}

# ["DEFAULT"] 相当于字典config的键,{}里的内容是键["DEFAULT"]的值。
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

# 把写好的对象写到一个文件里
# 把句柄configfile作为内容写入到xample.ini文件里。
with open('example.ini', 'w') as configfile:
    config.write(configfile)   # 通过config对象,调用write方法,把句柄configfile写入到example.ini文件里。

执行后example.ini文件的内容如下:
第二十四篇configparser(**)

文件内容与最开始的文件结构一致了,这样一个简单的配置文件就通过Python生成好了。 

 再来通过Python给生成还有更多块的配置文件

import configparser

config = configparser.ConfigParser()   # 实例出来一个对象,相当于创建了一个空字典config={}

# ["DEFAULT"] 相当于字典config的键,{}里的内容是键["DEFAULT"]的值。
# 相当于创建了一个[DEFAULT]块(指的是在配置文件里的块哦)
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['DEFAULT']['ForwardX11'] = 'yes'   # 也可以这样给字典里新增键值对


# 这个写法虽然与上面不一样,但是原理是一样的
# 首先config的键['bitbucket.org'] 对应一个空字典{}
# 这就相当于又创建了一个块[bitbucket.org](在配置文件里哦)
config['bitbucket.org'] = {}
# 给空字典{}里增加了一个键值对
config['bitbucket.org']['User'] = 'hg'


# 同理又创建了一个块[topsecret.server.com]
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
# 然后空字典{}里给它填值
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

# 把写好的对象写到一个文件里
# 把句柄configfile作为内容写入到xample.ini文件里。
with open('example.ini', 'w') as configfile:
    config.write(configfile)   # 通过config对象,调用write方法,把句柄configfile写入到example.ini文件里。

生成后的配置文件内容
第二十四篇configparser(**)
# 无注释版代码
import configparser

config = configparser.ConfigParser()   


config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['DEFAULT']['ForwardX11'] = 'yes'   


config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'


config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  
topsecret['ForwardX11'] = 'no'  


with open('example.ini', 'w') as configfile:
    config.write(configfile)   
View Code

相关文章: