configParser模块详谈
前言
使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configParser
configParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项
ConfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
ConfigParser
模块在python3中修改为configparser
.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同
该模块的作用 就是使用模块中的RawConfigParser()
、ConfigParser()
、 SafeConfigParser()
这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查 操作。配置文件有不同的片段组成和Linux中repo文件中的格式类似:
ini
1、ini配置文件格式如下:
#这是注释;这里也是注释[section0]key0 = value0
key1 = value1[section1]key2 = value2
key3 = value3
样例配置文件example.ini
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root host_port = 69[concurrent] thread = 10 processor = 20
2、section不能重复,里面数据通过section去查找,每个seletion下可以有多个key和vlaue的键值对,注释用英文分号(;)
configparser
1、python3里面自带configparser模块来读取ini文件
# python3 import configParser
敲黑板:python2的版本是Configparser
# python2 import ConfigParser
2、在pycharm里面,新建一个ini文件:右键New->File, 输入框直接写一个.ini后缀文件就行了,然后写数据
3、ConfigParser 初始化对象
使用ConfigParser 首选需要初始化实例,并读取配置文件:
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8")
4、注释里面有中文的话,这里代码跟python2是有点区别的,python2里面直接conf.read(cfgpath)就可以了,python3需要加个参数:encoding=”utf-8”
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8")
敲黑板:如果ini文件里面写的是数字,读出来默认是字符串
# coding:utf-8 # 作者:古风尘import configparser import os curpath = os.path.dirname(os.path.realpath(__file__)) cfgpath = os.path.join(curpath, "demo.ini") print(cfgpath) # demo.ini的路径# 创建管理对象 conf = configparser.ConfigParser()# 读ini文件 conf.read(cfgpath, encoding="utf-8") # python3# conf.read(cfgpath) # python2# 获取所有的section sections = conf.sections()print(sections) # 返回list items = conf.items('db') print(items) # list里面对象是元祖
运行结果:
D:\debug_p3\cfg\demo.ini
['db_host', 'concurrent','book']
[('db_port', '127.0.0.1'),
('db_user', 'root'),
('db_pass', 'root'),
('hosr_port', '69')]
ConfigParser 常用方法
获取section节点
1、获取所用的section节点
# 获取所用的section节点 import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") print(config.sections()) #运行结果 # ['db', 'concurrent','book']
2、获取指定section 的options。
即将配置文件某个section 内key 读取到列表中:
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") r = config.options("db") print(r) #运行结果 # ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']
3、获取指点section下指点option的值
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") r = config.get("db", "db_host") # r1 = config.getint("db", "k1") #将获取到值转换为int型 # r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型 # r3 = config.getfloat("db", "k3" ) #将获取到值转换为浮点型 print(r) #运行结果 # 127.0.0.1
4、获取指点section的所用配置信息
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") r = config.items("db") print(r) #运行结果 #[('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')]
5、修改某个option的值,如果不存在则会出创建
# 修改某个option的值,如果不存在该option 则会创建 import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") config.set("db", "db_port", "69") #修改db_port的值为69 config.write(open("ini", "w"))
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root[concurrent] thread = 10 processor = 20
import configparser config = configparser.ConfigParser() config.has_section("section") #是否存在该section config.has_option("section", "option") #是否存在该option
remove
1、如果想删除section中的一项,比如我想删除[email_163]下的port 这一行
# 删除一个 section中的一个 item(以键值KEY为标识) conf.remove_option('concurrent', "thread")
2、删除整个section这一项
conf.remove_section('concurrent')
3、删除section 和 option
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") config.remove_section("default") #整个section下的所有内容都将删除 config.write(open("ini", "w"))
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root[concurrent] thread = 10 processor = 20
add
1、新增一个section
# 添加一个select conf.add_section("emali_tel") print(conf.sections())
2、section里面新增key和value
# 往select添加key和value conf.set("emali_tel", "sender", "yoyo1@tel.com") conf.set("emali_tel", "port", "265")
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8") if not config.has_section("default"): # 检查是否存在sectionconfig.add_section("default") if not config.has_option("default", "db_host"): # 检查是否存在该optionconfig.set("default", "db_host", "1.1.1.1") config.write(open("ini", "w"))
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root[concurrent] thread = 10 processor = 20[default] db_host = 1.1.1.1
write写入
1、write写入有两种方式,一种是删除原文件内容,重新写入:w
conf.write(open(cfgpath, "w")) # 删除原文件重新写入
另外一种是在原文件基础上继续写入内容,追加模式写入:a
conf.write(open(cfgpath, "a")) # 追加模式写入
2、前面讲的remove和set方法并没有真正的修改ini文件内容,只有当执行conf.write()方法的时候,才会修改ini文件内容,举个例子:在ini文件上追加写入一项section内容
# coding:utf-8 import configparser import os curpath = os.path.dirname(os.path.realpath(__file__)) cfgpath = os.path.join(curpath, "cfg.ini") print(cfgpath) # cfg.ini的路径# 创建管理对象 conf = configparser.ConfigParser()# 添加一个select conf.add_section("emali_tel") print(conf.sections())# 往select添加key和value conf.set("emali_tel", "sender", "yoyo1@tel.com") conf.set("emali_tel", "port", "265") items = conf.items('emali_tel') print(items) # list里面对象是元祖 conf.write(open(cfgpath, "a")) # 追加模式写入
运行后会发现ini文件最后新增了写入的内容了
3、写入文件
以下的几行代码只是将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效
import configparser config = configparser.ConfigParser() config.read("ini", encoding="utf-8")
写回文件的方式如下:(使用configparser的write方法)
config.write(open("ini", "w")) # 删除原文件重新写入
综合实例:
#coding=utf-8import ConfigParserdef writeConfig(filename):config = ConfigParser.ConfigParser() #创建ConfigParser实例# set dbsection_name = 'db'config.add_section( section_name ) #添加一个配置文件节点(strconfig.set( section_name, 'dbname', 'MySQL')config.set( section_name, 'host', '127.0.0.1')config.set( section_name, 'port', '80')config.set( section_name, 'password', '123456')config.set( section_name, 'databasename', 'test')# set appsection_name = 'app'config.add_section( section_name )config.set( section_name, 'loggerapp', '192.168.20.2')config.set( section_name, 'reportapp', '192.168.20.3')# write to fileconfig.write( open(filename, 'a') ) #写入配置文件def updateConfig(filename, section, **keyv):config = ConfigParser.ConfigParser()config.read(filename)print config.sections() #返回配置文件中节序列for section in config.sections():print "[",section,"]"items = config.items(section) #返回某个项目中的所有键的序列for item in items:print "\t",item[0]," = ",item[1]print config.has_option("dbname", "MySQL")print config.set("db", "dbname", "11") #设置db节点中,键名为dbname的值(11)print "..............."for key in keyv:print "\t",key," = ", keyv[key]config.write( open(filename, 'r+') )if __name__ == '__main__':file_name = 'test.ini'writeConfig(file_name)updateConfig(file_name, 'app', reportapp = '192.168.100.100')print "end__"
转载于:https://www.cnblogs.com/gufengchen/p/10929463.html
configParser模块详谈相关推荐
- python【Configparser解析配置文件库】Python3中的configparser模块
文章目录 configparser模块简介 看一下configparser生成的配置文件的格式 现在看一下类似上方的配置文件是如何生成的 读文件内容 修改 configparser模块简介 该模块适用 ...
- configparser模块和PyYAML模块生成和修改配置文件
文章目录: 1 configparser模块 2 PyYAML模块 2.2 yaml基本使用 2.2.1 使用yaml.load()读取yaml文件,并获取其中的配置信息 2.2.2 使用yaml.l ...
- python小白-day6 ConfigParser模块
ConfigParser模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser. 来看一个好多软件的常见文档格式如下 用python生成上文档 ...
- python中configparser_python中confIgparser模块学习
python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...
- Python基础(14)_python模块之configparser模块、suprocess
9.configparser模块 模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值). 常见的软件格式文档格式如下: 1 ...
- 小白的Python之路 day5 configparser模块的特点和用法
configparser模块的特点和用法 一.概述 主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser.在python2.x版本中为Conf ...
- python:实例化configparser模块读写配置文件
之前的博客介绍过利用python的configparser模块读写配置文件的基础用法,这篇博客,介绍下如何实例化,方便作为公共类调用. 实例化的好处有很多,既方便调用,又降低了脚本的维护成本,而且提高 ...
- Python 常用函数 configparser模块
使用ConfigParser模块读写ini文件 ConfigParserPython的ConfigParser Module中定义了3个类对INI文件进行操作.分别是RawConfigParser.C ...
- python中configparser详解_Python中的ConfigParser模块使用详解
1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有的section,并以列表的形式返回 -options(section) 得到该sect ...
最新文章
- python模块之json,pickle
- 决定神经网络迭代次数的两个因素
- DataBinder.Eval用法收集
- 如何安装docker-compose
- 一个SAP成都研究院开发工程师 2020 年的所有文章列表
- java openresty 调用_玩转 OpenResty 协程 API
- 科创板5只股发行市盈率高达40、50倍,会有什么风险?
- 在矩池云上复现 PaddleGAN 照片转油画风格教程
- java连接mysql数据库增删改查操作记录
- 说说浏览器缓存里的websql与 indexeddb
- 命令行编译工具NMAKE
- 皕杰报表里的排序问题
- 新兴的外贸获客系统:孚盟360度获客矩阵,高效助力外贸客户开发
- 【2073】三角形面积
- LWIP协议栈设计与实现笔记:
- 多功能起名查重工具微信小程序源码
- JAVA五子棋单机版
- 玩转Java8Stream之函数式接口
- Android P 图形显示系统(四) Android VirtualDisplay解析
- ibooks打开iframe引用的html文件乱码
热门文章
- jxl简析[ http://www.emlog.net/fei ]
- 2.struts1.x中的异常处理
- sort(()={return Math.random()-0.5)}乱序数组不准确
- 461在全志r16平台tinav3.0系统下使用地磁计QMC5883L
- [Elasticsearch] 邻近匹配 (二) - 多值字段,邻近程度与相关度
- Java Servlet生成JSON格式数据并用jQuery显示
- SH1B LMR62014XMFE/NOPB
- json_encode用法
- Elasticsearch聚合 之 Date Histogram聚合
- no acceptable C compiler found in $PATH