Python ConfigParser模块的使用示例


Posted in Python onOctober 12, 2020

前言

在做项目的时候一些配置文件都会写在settings配置文件中,今天在研究"州的先生"开源文档写作系统-MrDoc的时候,发现部分配置文件写在config.ini中,并利用configparser进行相关配置文件的读取及修改。

一、ConfigParser模块简介

该模块适用于配置文件的格式与windows ini文件类似,是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Atlan
[topsecret.server.com]
Port = 50022
ForwardX11 = no

括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。

二、ConfigParser模块使用

1.写入操作

代码如下:

import configparser #引入模块
​
config = configparser.ConfigParser()  #类中一个方法 #实例化一个对象
​
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9',
           'ForwardX11':'yes'
           } #类似于操作字典的形式
​
config['bitbucket.org'] = {'User':'Atlan'} #类似于操作字典的形式
​
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
​
with open('example.ini', 'w') as configfile:
​
  config.write(configfile) #将对象写入文件
以上代码做个简单的解释,和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面,跟一个section,在紧跟着设置section的属性(类似字典的形式)
 
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9',
           'ForwardX11':'yes'
           } #类似于操作字典的形式
#config后面跟的是一个section的名字,section的段的内容的创建类似于创建字典。类似与字典当然还有别的操作方式啦!
config['bitbucket.org'] = {'User':'Atlan'} #类似于最经典的字典操作方式

2.读取操作

import configparser
config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
print(config.sections())    # []
config.read('example.ini',encoding='utf-8')
print(config.sections())    #  ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print('DEFAULT' in config) # True
print(config['bitbucket.org']["user"]) # Atlan
​
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11']) #no
​
print(config['bitbucket.org'])     #<Section: bitbucket.org>
for key in config['bitbucket.org']:   # 注意,有default会默认default的键
  print(key)             #user serveraliveinterval compression compressionlevel forwardx11
​
# 同for循环,找到'bitbucket.org'下所有键 ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.options('bitbucket.org')) 
​
print(config.items('bitbucket.org'))  #找到'bitbucket.org'下所有键值对 [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'Atlan')]
​
print(config.get('bitbucket.org','compression')) # yes    get方法Section下的key对应的value
print(config.getboolean('bitbucket.org','compression')) # True

3.修改操作

import configparser
​
config = configparser.ConfigParser()
​
config.read('example.ini',encoding='utf-8') #读文件
​
config.add_section('yuan') #添加section
​
config.remove_section('bitbucket.org') #删除section
config.remove_option('topsecret.server.com',"forwardx11") #删除一个配置项
# 修改某个option的值,如果不存在该option 则会创建
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
#写回文件
config.write(open("example.ini", "w"))
# 写到其他文件
with open('new2.ini','w') as f:
   config.write(f)

以上就是Python ConfigParser模块的使用示例的详细内容,更多关于Python ConfigParser模块的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python 字符串操作实现代码(截取/替换/查找/分割)
Jun 08 Python
python类继承与子类实例初始化用法分析
Apr 17 Python
Python处理文本文件中控制字符的方法
Feb 07 Python
python 换位密码算法的实例详解
Jul 19 Python
Python 判断是否为质数或素数的实例
Oct 30 Python
利用ImageAI库只需几行python代码实现目标检测
Aug 09 Python
python+django+rest框架配置创建方法
Aug 31 Python
python利用datetime模块计算程序运行时间问题
Feb 20 Python
ITK 实现多张图像转成单个nii.gz或mha文件案例
Jul 01 Python
pycharm 多行批量缩进和反向缩进快捷键介绍
Jan 15 Python
django inspectdb 操作已有数据库数据的使用步骤
Feb 07 Python
一起来学习Python的元组和列表
Mar 13 Python
python修改微信和支付宝步数的示例代码
Oct 12 #Python
教你如何用python操作摄像头以及对视频流的处理
Oct 12 #Python
Django限制API访问频率常用方法解析
Oct 12 #Python
Python confluent kafka客户端配置kerberos认证流程详解
Oct 12 #Python
Django如何使用asyncio协程和ThreadPoolExecutor多线程
Oct 12 #Python
使用Python中tkinter库简单gui界面制作及打包成exe的操作方法(二)
Oct 12 #Python
使用Python将xmind脑图转成excel用例的实现代码(一)
Oct 12 #Python
You might like
关于时间计算的结总
2006/12/06 PHP
PHP脚本中include文件出错解决方法
2008/11/20 PHP
解析用PHP实现var_export的详细介绍
2013/06/20 PHP
php 生成自动创建文件夹并上传文件的示例代码
2014/03/07 PHP
PHP使用Alexa API获取网站的Alexa排名例子
2014/06/12 PHP
PHP加密技术的简单实现
2016/09/04 PHP
PHP PDOStatement::setAttribute讲解
2019/02/01 PHP
很多人都是用下面的js刷新站IP和PV
2008/09/05 Javascript
关于jQuery $.isNumeric vs. $.isNaN vs. isNaN
2013/04/15 Javascript
ie中js创建checkbox默认选中问题探讨
2013/10/21 Javascript
JS调用页面表格导出excel示例代码
2014/03/18 Javascript
jQuery不兼容input的change事件问题解决过程
2014/12/05 Javascript
JQuery中基础过滤选择器用法实例分析
2015/05/18 Javascript
jQuery实现强制cookie过期方法汇总
2015/05/22 Javascript
JS验证IP,子网掩码,网关和MAC的方法
2015/07/02 Javascript
利用JS生成博文目录及CSS定制博客
2016/02/10 Javascript
Java遍历集合方法分析(实现原理、算法性能、适用场合)
2016/04/25 Javascript
JS根据生日月份和日期计算星座的简单实现方法
2016/11/24 Javascript
微信小程使用swiper组件实现图片轮播切换显示功能【附源码下载】
2017/12/12 Javascript
angular4中*ngFor不能对返回来的对象进行循环的解决方法
2018/09/12 Javascript
nodejs中实现用户注册路由功能
2019/05/20 NodeJs
[02:28]DOTA2 2017国际邀请赛小组赛回顾
2017/08/09 DOTA
Python3搜索及替换文件中文本的方法
2015/05/22 Python
对python pandas 画移动平均线的方法详解
2018/11/28 Python
使用Python正则表达式操作文本数据的方法
2019/05/14 Python
python使用 zip 同时迭代多个序列示例
2019/07/06 Python
Python中一个for循环循环多个变量的示例
2019/07/16 Python
Python 使用指定的网卡发送HTTP请求的实例
2019/08/21 Python
Python英文文章词频统计(14份剑桥真题词频统计)
2019/10/13 Python
python实现的分析并统计nginx日志数据功能示例
2019/12/21 Python
python文件操作seek()偏移量,读取指正到指定位置操作
2020/07/05 Python
python开发入门——列表生成式
2020/09/03 Python
澳大利亚领先的在线机械五金、园艺和存储专家:Edisons
2018/03/24 全球购物
乡下人家教学反思
2014/02/01 职场文书
个人担保书格式范文
2014/05/12 职场文书
MySQL主从复制断开的常用修复方法
2021/04/07 MySQL