python -- PyYAML和configparser模块
PyYAML模块
PyYAML模块并非标准库,所以需要另行安装。
跟着官网学习。
configparser模块
可以编辑类似MySQL、Nginx等的配置文件
以下是一个配置文件的样板
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
新建一个ini的文件,用configparser模块完成
#_*_coding:utf-8_*_
# Python2里configparser是叫ConfigParser
import configparser
# 将模块赋值给变量config
config = configparser.ConfigParser()
# 类似一个字典的模式
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
# 这里先建立一个空字典,为了演示,空字典是可以再加入内容的效果
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
# 这句代码的意思是将上一句的字典赋值给topsecret这个变量而已,为了减少代码输入,没有别的用意
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
# 最后在DEFAULT中再加入一个值
config['DEFAULT']['ForwardX11'] = 'yes'
# 最后写入文件
with open('example.ini', 'w') as configfile:
config.write(configfile)
读取文件信息,先执行以下上面的代码生成一个example.ini文件。
import configparser
config = configparser.ConfigParser()
# 先读一个文件进来,再看效果
config.read('example.ini')
# 不打印default值
print(config.sections())
# 打印default值的方法
print(config.defaults())
# 打印节点下的值内容
print(config['bitbucket.org']['user'])
修改文件信息
import configparser
config = configparser.ConfigParser()
# 先读取一个example.ini文件的内容
config.read('example.ini')
# 判断是否是‘test’节点
sec = config.has_section('test') # 返回值是False
# 删除‘bitbucket.org’节点内容
config.remove_section('bitbucket.org')
# 增加一个group节点
config.add_section('group')
# 在group节点下增加两个不同的值
config.set('group', 'k1', '1234565')
config.set('group', 'age', '30')
# 删除group节点下的age值,包含age自己
config.remove_option('group', 'age')
# 回写原文件,或另存为新文件
# 由于文件的内容已经在内存里,所以直接回写源文件也是可以直接操作
config.write(open('example.ini', 'w'))
本文详细介绍了PyYAML和configparser模块的使用方法,包括如何安装PyYAML,利用configparser创建、读取和修改配置文件。通过具体实例展示了如何新建、读取和修改配置文件,适用于Python配置管理的学习与实践。
199

被折叠的 条评论
为什么被折叠?



