python -- PyYAML和configparser模块

本文详细介绍了PyYAML和configparser模块的使用方法,包括如何安装PyYAML,利用configparser创建、读取和修改配置文件。通过具体实例展示了如何新建、读取和修改配置文件,适用于Python配置管理的学习与实践。

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'))

转载于:https://www.cnblogs.com/gzz041/p/7207196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值