一、简介

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模块的更多相关文章

  1. python模块: hashlib模块, configparse模块, logging模块,collections模块

    一. hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用 ...

  2. Python模块-configparse模块

    configparse模块用来解析配置文件 配置文件 [DEFAULT] port = 3306 socket = /tmp/mysql.sock [mysqldump] max_allowed_pa ...

  3. 第十一节:configParse模块

    作用:配置文件解析模块,用来增删改查配置文件内容,不区分大小写 配置文件案例: tets.ini [模块] key=value import configparser config = configp ...

  4. Python常用内建模块

    Python常用内建模块 datetime 处理日期和时间的标准库. 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import da ...

  5. 转:Yii实战中8个必备常用的扩展,模块和widget

    转载自:http://www.yiiframework.com/wiki/180/yii8/ 在经过畅K网的实战后,总结一下在Yii的项目中会经常用到的组件和一些基本的使用方法,分享给大家,同时也给自 ...

  6. python-Day5-深入正则表达式--冒泡排序-时间复杂度 --常用模块学习:自定义模块--random模块:随机验证码--time & datetime模块

    正则表达式   语法:             mport re #导入模块名 p = re.compile("^[0-9]") #生成要匹配的正则对象 , ^代表从开头匹配,[0 ...

  7. python configparse模块&xml模块

    configparse模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser. [DEFAULT] serveraliveinterval = ...

  8. Python之常用模块--collections模块

    认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...

  9. 【转】Python3 configparse模块(配置)

    [转]Python3 configparse模块(配置) ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(s ...

随机推荐

  1. 超实用!手把手教你如何用MSF进行后渗透测试!

    在对目标进行渗透测试的时候,通常情况下,我们首先获得的是一台web服务器的webshell或者反弹shell,如果权限比较低,则需要进行权限提升:后续需要对系统进行全面的分析,搞清楚系统的用途:如果目 ...

  2. [原]globalmapper设置高程配色(globalmapper自定义配色方案)

    1.使用的globalmapper版本:1.8以上(之前的版本也应该支持) 2.将全球DEM加载进去 (零时找的小DEM  全球7级) 3.右击此处,选择“高程图例选项” 4.选择 配置-着色器选项 ...

  3. odoo开发笔记 -- docker容器打包到另一台服务器部署异常

    场景描述: odoo.conf文件指定了数据库配置,如果docker打包的时候,没注意,新环境启动该镜像,会导致并没有连接本地的数据库,如果你配置文件中的数据库地址,当前这台服务器也可以访问到,那么问 ...

  4. jQuery 取值操作

    模板使用: https://startbootstrap.com/themes/sb-admin-2/ 使用的 bootstrap 模块 ,上面的这个网站可以下载 select 取值 <sele ...

  5. 【转】Revit二次开发——读取cad中的文字信息

    Revit读取cad的文字信息需要借助Teigha的开源dll,在程序中添加下图中红色框的dll文件的引用,其他的dll文件全部放在同一个文件夹中即可,运行的时候,会自动把这些dll文件全部复制到bi ...

  6. idea 出现 bootstrap.properties 中的内容不能识别

    错误截图如下 依赖库引用问题 第一种: <dependency> <groupId>org.springframework.cloud</groupId> < ...

  7. notepad++去掉红色波浪线

    1 在notepad++的首页上找到插件菜单,并点击打开插件设置的下拉菜单.   2 下拉菜单中有一个菜单项是DSpellCheck,这个菜单项的子项中有一项是Spell Check Document ...

  8. c# Mono.Cecil IL方式 读MethodBody

    using Kufen.Common.Definitions; using Mono.Cecil; using System; using System.Collections.Generic; us ...

  9. Window及document对象

    注:页面上元素name属性以及JavaScript引用的名称必须一致包括大小写 否则会提示你1个错误信息 "引用的元素为空或者不是对象" 一.Window对象 ---------- ...

  10. web page popup window model

    jQuery UI dialog: https://jqueryui.com/dialog/ Semantic UI https://semantic-ui.com/modules/modal.htm ...