常用模块 - configparse模块
一、简介
configparser模块在Python中是用来读取配置文件的,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节点(section),每个节可以有多个参数(键=值)。
二、生成配置文件
#! /usr/bin/env python3
# -*- coding:utf-8 -*- # Author : mayi
# Blog : http://www.cnblogs.com/mayi0312/
# Date : 2019/4/3
# Name : test01
# Software : PyCharm
# Note : 用于测试configparser模块的功能
# 导入模块
import configparser config = configparser.ConfigParser()
"""生成configparser配置文件 ,字典的形式"""
"""第一种写法"""
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''}
"""第二种写法"""
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
"""第三种写法"""
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes'
"""写入后缀为.ini的文件"""
with open('example.ini', 'w') as configfile:
config.write(configfile)
运行后,文件“example.ini”中的结果:
[DEFAULT]
compression = yes
compressionlevel = 9
serveraliveinterval = 45
forwardx11 = yes [bitbucket.org]
user = hg [topsecret.server.com]
host port = 50022
forwardx11 = no
三、解析配置文件
读取configparser配置文件的实例
#! /usr/bin/env python3
# -*- coding:utf-8 -*- # Author : mayi
# Blog : http://www.cnblogs.com/mayi0312/
# Date : 2019/4/3
# Name : test01
# Software : PyCharm
# Note : 用于测试configparser模块的功能
# 导入模块
import configparser config = configparser.ConfigParser()
# 读取配置文件
config.read("example.ini") print("所有节点==>", config.sections()) print("包含实例范围默认值的词典==>", config.defaults()) for item in config["DEFAULT"]:
print("循环节点topsecret.server.com下所有option==>", item) print("bitbucket.org节点下所有option的key,包括默认option==>", config.options("bitbucket.org")) print("输出元组,包括option的key和value", config.items('bitbucket.org')) print("bitbucket.org下user的值==>", config["bitbucket.org"]["user"]) # 方式一 topsecret = config['bitbucket.org']
print("bitbucket.org下user的值==>", topsecret["user"]) # 方式二 print("判断bitbucket.org节点是否存在==>", 'bitbucket.org' in config) print("获取bitbucket.org下user的值==>", config.get("bitbucket.org","user")) print("获取option值为数字的:host port=", config.getint("topsecret.server.com","host port"))
运行结果:
所有节点==> ['bitbucket.org', 'topsecret.server.com']
包含实例范围默认值的词典==> OrderedDict([('compression', 'yes'), ('compressionlevel', ''), ('serveraliveinterval', ''), ('forwardx11', 'yes')])
循环节点topsecret.server.com下所有option==> compression
循环节点topsecret.server.com下所有option==> compressionlevel
循环节点topsecret.server.com下所有option==> serveraliveinterval
循环节点topsecret.server.com下所有option==> forwardx11
bitbucket.org节点下所有option的key,包括默认option==> ['user', 'compression', 'compressionlevel', 'serveraliveinterval', 'forwardx11']
输出元组,包括option的key和value [('compression', 'yes'), ('compressionlevel', ''), ('serveraliveinterval', ''), ('forwardx11', 'yes'), ('user', 'hg')]
bitbucket.org下user的值==> hg
bitbucket.org下user的值==> hg
判断bitbucket.org节点是否存在==> True
获取bitbucket.org下user的值==> hg
获取option值为数字的:host port= 50022
删除配置文件section和option的实例(默认分组有参数时无法删除,但可以先删除下面的option,再删分组)
#! /usr/bin/env python3
# -*- coding:utf-8 -*- # Author : mayi
# Blog : http://www.cnblogs.com/mayi0312/
# Date : 2019/4/3
# Name : test01
# Software : PyCharm
# Note : 用于测试configparser模块的功能
# 导入模块
import configparser config = configparser.ConfigParser()
# 读取配置文件
config.read("example.ini") config.remove_section("bitbucket.org")
"""删除分组"""
config.remove_option("topsecret.server.com", "host port")
"""删除某组下面的某个值"""
config.write(open('example.ini', "w"))
运行后,文件“example.ini”中的结果:
[DEFAULT]
compression = yes
compressionlevel = 9
serveraliveinterval = 45
forwardx11 = yes [topsecret.server.com]
forwardx11 = no
修改配置文件
#! /usr/bin/env python3
# -*- coding:utf-8 -*- # Author : mayi
# Blog : http://www.cnblogs.com/mayi0312/
# Date : 2019/4/3
# Name : test01
# Software : PyCharm
# Note : 用于测试configparser模块的功能
# 导入模块
import configparser config = configparser.ConfigParser()
# 读取配置文件
config.read("example.ini") config.add_section("new_section")
"""新增分组"""
config.set("DEFAULT", "compressionlevel", "")
"""设置DEFAULT分组下compressionlevel的值为110"""
config.write(open('example.ini', "w"))
运行后,文件“example.ini”中的结果:
[DEFAULT]
compression = yes
compressionlevel = 110
serveraliveinterval = 45
forwardx11 = yes [topsecret.server.com]
forwardx11 = no [new_section]
常用模块 - configparse模块的更多相关文章
- python模块: hashlib模块, configparse模块, logging模块,collections模块
一. hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用 ...
- Python模块-configparse模块
configparse模块用来解析配置文件 配置文件 [DEFAULT] port = 3306 socket = /tmp/mysql.sock [mysqldump] max_allowed_pa ...
- 第十一节:configParse模块
作用:配置文件解析模块,用来增删改查配置文件内容,不区分大小写 配置文件案例: tets.ini [模块] key=value import configparser config = configp ...
- Python常用内建模块
Python常用内建模块 datetime 处理日期和时间的标准库. 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import da ...
- 转:Yii实战中8个必备常用的扩展,模块和widget
转载自:http://www.yiiframework.com/wiki/180/yii8/ 在经过畅K网的实战后,总结一下在Yii的项目中会经常用到的组件和一些基本的使用方法,分享给大家,同时也给自 ...
- python-Day5-深入正则表达式--冒泡排序-时间复杂度 --常用模块学习:自定义模块--random模块:随机验证码--time & datetime模块
正则表达式 语法: mport re #导入模块名 p = re.compile("^[0-9]") #生成要匹配的正则对象 , ^代表从开头匹配,[0 ...
- python configparse模块&xml模块
configparse模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser. [DEFAULT] serveraliveinterval = ...
- Python之常用模块--collections模块
认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...
- 【转】Python3 configparse模块(配置)
[转]Python3 configparse模块(配置) ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(s ...
随机推荐
- Mini UI tree上万复杂节点加载缓慢处理设计
最直接的方式是设置tree顶级不展开,可以解决一定效率. expandOnLoad Boolean/Number 加载后是否展开.比如:true展开所有节点:0展开第一级节点.以此类推. 1. 解决问 ...
- Torch-Models 别人训练的FastNeuralStyle
This is the pink style's image: This is the triangle one: The fire ones come from this image: And th ...
- tomcat高并发优化的参数优化并查看tomcat线程数
在Tomcat配置文件conf下面 server.xml 中的配置中和连接数相关的参数有: minProcessors:最小空闲连接线程数,用于提高系统处理性能,默认值为10 maxProcessor ...
- Q-Dir – 布局灵活的文件管理,强烈推荐
Q-dir 是轻量的文件管理器,特点鲜明,各种布局视图切换灵活,默认四个小窗口组成一个大窗口,操作快捷.软件虽小,却非常好用 下载地址: https://www.softwareok.com/?Dow ...
- Consider defining a bean of type 'com.*.*.feign.*FeignClient' in your configuration.
Description: Field *FeignClient in com.*.*.service.* required a bean of type '***********' that coul ...
- HTML和CSS个人笔记
目录 定位 文字显示在图片上 ul的li元素的小圆点换成图片 关于Bootstrap的响应式 不要在container之外使用row 不要使用padding的时候固定高度 不要使用<hr p标签 ...
- Qt5.QtCreator_屏蔽警告
ZC:注意: 修改了这个配置的话,如果有多个Qt进程的话,它不会自动同步各个进程中的值,可能是 以最后保存的为准(需要注意 ! !) 1.QtCreator屏蔽指定警告 - weixin_409542 ...
- QQ自动强制加好友代码html
鲜为人知的QQ自动强制加好友代码 是的,你也许见过强行聊天的代码: tencent://Message/?Uin=574201314&websiteName=www.oicqzone.com& ...
- oracle全库查找是否有某个值
在scott用户下面,搜索含有'要找的值'的数据的表和字段穷举法: declare v_Sql ); v_count number; begin for xx in (select t.OWNER, ...
- 使用docker-compose快速搭建gitlab
1. 准备工作: centos7 [root@dev_vonedao_95 gitlab]# docker -v Docker version , build 633a0ea [root@dev_vo ...