PyYAML和configparser模块讲解

Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 

ymal主要用于配置文件。

ConfigParser模块

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

比如mysql,nginx,php配置文件都是这种格式

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

导入模块,在py2里是import ConfigParser

在py3里都是小写了import configparser

我们现在来生成一个example.ini配置文件

import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
 
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret
= config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'

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

我现在再把这个文件读出来:

删除:

修改:

http://www.cnblogs.com/alex3714/articles/5161349.html

原文地址:https://www.cnblogs.com/itfat/p/7491908.html