configparser模块是一种文件数据处理格式的方法,常用与生成、解析或修改.ini配置文件
1.常见.ini文件格式内容如下
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
2. configparser模块的简单使用
# -*- coding:utf-8 -*-# Author:Wong Du'''configparser模块是一种文件数据处理格式方法,常用于生成和修改常见配置文档,文件后缀名为.ini'''import configparserconfig = configparser.ConfigParser() # ConfigParser implementing interpolation,生成对象# 姿势一config["DEFAULT"] = { 'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} # 配置缺省信息# 姿势二config['bitbucket.org'] = {}config['bitbucket.org']['User'] = 'hg'config['DEFAULT']['ForwardX11'] = 'yes'# 姿势三config['topsecret.server.com'] = {}topsecret = config['topsecret.server.com']topsecret['Host Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same here# 写入到文件当中with open('example.ini', 'w') as configfile: config.write(configfile)