configparser模块

configparser模块是一种文件数据处理格式的方法,常用与生成、解析或修改.ini配置文件

  1.常见.ini文件格式内容如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

  2. configparser模块的简单使用

# -*- coding:utf-8 -*-
# Author:Wong Du

'''
configparser模块是一种文件数据处理格式方法,
常用于生成和修改常见配置文档,文件后缀名为.ini
'''

import configparser
config = 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 parser
topsecret['ForwardX11'] = 'no'  # same here

# 写入到文件当中
with open('example.ini', 'w') as configfile:
    config.write(configfile)

原文地址:https://www.cnblogs.com/Caiyundo/p/9438030.html