day5-PyYaml和configparser模块
概述
PyYaml模块
YAML是一种数据序列化(serialization )语言,YAML 语言比 XML 、JSON 更容易编写与阅读,是一种比较理想的脚本语言使用数据格式,例如配置文件格式等。
Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档
configparser模块
而configparser也用于生成和修改常见配置文档,当前模块的名称在python3.x版本中变更为configparser。
注:Parser汉译为“解析”之意。
配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
为了更好的理解,我们先了解一下配置文件的组成及命名:配置文件(INI文件)由节(section)、键、值组成。
样例配置文件example.ini
[DEFALUT] compressionlevel = 9 serveraliveinterval = 45 compression = yes forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
1.生成配置文件
import configparser
#创建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['HostPort']='50022'
topsecret['ForwardX11']='no'
#给全局配置组赋值
config['DEFAULT']['ForwardX11']='yes'
#把配置的内容写入一个配置文件中
with open('example.ini','w')as configfile:
config.write(configfile)
#输出
[DEFAULT]
compressionlevel=9
compression=yes
serveraliveinterval=45
forwardx11=yes
[bitbucket.org]
user=hg
[topsecret.server.com]
hostport=50022
forwardx11=no
2.读取配置文件
2.1读取配置组
>>>import configparser
>>>conf=configparser.ConfigParser()
#不读取配置文件
>>> config.sections()
#组名列表为空
[]
#读取配置文件
>>>conf.read("example.ini")
#返回配置文件名
['example.ini']
#返回除默认配置组的其他组名
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>>conf.defaults()
OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')])
2.2判断组名是否存在
>>>'bitbucket.org' in config #组名存在,返回True True >>>'bytebong.com' in config #组名不存在,返回False False
2.3读取组内的值
>>>config['bitbucket.org']['User'] #读取"bitbucket.org"配置组中的值 或 config.get('bitbucket.org','User')
'hg'
>>>config['DEFAULT']['Compression'] #读取默认配置组中的值
'yes'
>>>topsecret=config['topsecret.server.com'] #把配置组赋给一个对象
>>>topsecret['ForwardX11'] #通过对象获取值
'no'
>>>topsecret['Port'] #通过对象获取值
'50022'
>>>config['bitbucket.org']['ForwardX11'] #
'yes'
2.4循环获取组内的key值
for key in config['bitbucket.org']: #循环打印bitbucket.org组下的key值
print(key)
#输出,打印bitbucket.org组和默认组的key值
user
compressionlevel
compression
serveraliveinterval
forwardx11
configparser增删改查语法

浙公网安备 33010602011771号