PyYAML模块和ConfigParser模块

两模块都是用来处理配置文件

PyYAML可参考 http://pyyaml.org/wiki/PyYAMLDocumentation

常见的文档格式,eg:

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

[bitbucket.org]
User = hg

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

用configparser生成这样的文件

import configparer  # Python2 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'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'

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

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('example.ini')
['example.ini']
>>> print(config.sections)
<bound method RawConfigParser.sections of <configparser.ConfigParser object at 0x000001FC2367EFD0>>
>>> print(config.sections())
['bitbucket.org', 'topsecret.server.com']
>>> print(config.defaults())
OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')])
>>> print(config['bitbucket.org'])
<Section: bitbucket.org>
>>> print(config['bitbucket.org']['user'])
hg
>>> sec = config.remove_section('bitbucket.org') # 删
>>> config.write(open('exmple.cfg', 'w'))

猜你喜欢

转载自www.cnblogs.com/allenzhang-920/p/9226549.html