一、简介

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. 对回溯算法的理解(以数独游戏为例,使用c++实现)

    算法思想: 数独游戏的规则: 每一行都用到1.2.3.4.5.6.7.8.9位置不限: 每一列都用到1.2.3.4.5.6.7.8.9位置不限: 每3×3的格子(共九个这样的格子)都用到1.2.3.4 ...

  2. Video Architecture Search

    Video Architecture Search 2019-10-20 06:48:26 This blog is from: https://ai.googleblog.com/2019/10/v ...

  3. [python]pypy优化python性能

    下载地址:https://pypy.org/download.html # python2.7版本 yum install pypy # python3.6版本https://bitbucket.or ...

  4. 删除DB2实例下的数据库

    db2ilist 查看所有实例  db2 get instance 查看当前连接的实例 db2 list db directory 查看当前实例下连接的数据库 ==================== ...

  5. win10安装grafana

    1.下载grafana-6.2.5.windows-amd64.msi 2.以管理员身份打开CMD 3.输入 msiexec /i 程序的完整路径 msiexec /i xxx.msi

  6. python-- python threadpool 的前世今生

    引出 首先需要了解的是threadpool 的用途,他更适合于用到一些大量的短任务合集,而非一些时间长的任务,换句话说,适合大量的CPU密集型短任务,那些消耗时间较长的IO密集型长任务适合用协程去解决 ...

  7. 带有Q_OBJECT的类要放在头文件的第一个类位置,否则可能无法moc

    如果头文件中有多个类,带有Q_OBJECT的类要放在头文件的第一个类位置,否则可能无法moc

  8. mysql 得到指定时间段的日期

    set @startDate='2019-01-01'; set @endDate='2019-04-01'; DAY) AS DAY FROM ( SELECT a.a ) AS a ) AS b ...

  9. Qt开发经验小技巧71-80

    在我们使用QList.QStringList.QByteArray等链表或者数组的过程中,如果只需要取值,而不是赋值,强烈建议使用 at() 取值而不是 [] 操作符,在官方书籍<C++ GUI ...

  10. CentOS7下Redis的安装与使用

    一.安装过程 1.准备工作(安装gcc依赖) # yum install gcc-c++ 2.下载并解压源码包 # cd /usr/local # wget http://download.redis ...