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", "") #修改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", "")
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
if not config.has_section("default"): # 检查是否存在section
config.add_section("default")
if not config.has_option("default", "db_host"): # 检查是否存在该option
config.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", "")
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-8 import ConfigParser def writeConfig(filename):
config = ConfigParser.ConfigParser() #创建ConfigParser实例
# set db
section_name = 'db'
config.add_section( section_name ) #添加一个配置文件节点(str
config.set( section_name, 'dbname', 'MySQL')
config.set( section_name, 'host', '127.0.0.1')
config.set( section_name, 'port', '')
config.set( section_name, 'password', '')
config.set( section_name, 'databasename', 'test') # set app
section_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 file
config.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", "") #设置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__"
configParser模块详谈的更多相关文章
- configparser模块
configparser模块 echo $@ $# $? $* configparse用于处理特定格式的文件,其本质上利用open来操作文件(比如配置文件) **********配置文件***** ...
- 用ConfigParser模块读写配置文件——Python
对于功能较多.考虑用户体验的程序,配置功能是必不可少的,如何存储程序的各种配置? 1)可以用全局变量,不过全局变量具有易失性,程序崩溃或者关闭之后配置就没了,再者配置太多,将变量分配到哪里也是需要考虑 ...
- Python自动化测试 -ConfigParser模块读写配置文件
C#之所以容易让人感兴趣,是因为安装完Visual Studio, 就可以很简单的直接写程序了,不需要做如何配置. 对新手来说,这是非常好的“初体验”, 会激发初学者的自信和兴趣. 而有些语言的开发环 ...
- Python学习笔记——基础篇【第六周】——PyYAML & configparser模块
PyYAML模块 Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 常用模块之Co ...
- Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...
- 小白的Python之路 day5 configparser模块的特点和用法
configparser模块的特点和用法 一.概述 主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser.在python2.x版本中为Conf ...
- configparser模块的常见用法
configparser模块用于生成与windows.ini文件类似格式的配置文件,可以包含一节或多节(section),每个节可以有一个或多个参数(键=值) 在学习这个模块之前,先来看一个经常见到的 ...
- day20 hashlib、hmac、subprocess、configparser模块
hashlib模块:加密 import hashlib# 基本使用cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))print(cipher.h ...
- python封装configparser模块获取conf.ini值(优化版)
昨天晚上封装了configparser模块,是根据keyname获取的value.python封装configparser模块获取conf.ini值 我原本是想通过config.ini文件中的sect ...
随机推荐
- [原创]Nodejs 远程执行linux shell
分享几个基于nodejs远程执行linux shell的函数 参数说明: ips - 一个存有IP地址的数组对象 /** * Created by kevalin on 2015/4/27. */ v ...
- .net 向新页面跳转的语句
1. href='##' onclick=\"window.open('../DataSplit/DrugInfo_ManualVersionViewNew.aspx?id=" + ...
- JAVA基础系列(一) 概述与相关概念
万事开头难,来这个平台上已经有一段时间了,看到了很多高质量的文章,也很喜欢这种简约的风格.一直也想把自己的零散的知识体系组织起来,但苦于自己拙劣的文笔和不成流派的风格让大家笑话,直到现在才开始.可是从 ...
- Golang自带的http包的路由规则问题
1.调用下面的方法开启一个http监听服务http.HandleFunc("/hello/", helloHandler)err := http.ListenAndServe(&q ...
- Struts2 源码分析-----Hello world
今天第一天学习struts2,没学过怎么办,那当然是helloworld.感觉嘛,学习的基本流程都差不多,就是helloworld,开发环境,然后就是逐个按照知识点打demo,打着打着你就会发现str ...
- [转]linux远程登入不需要密码
如何通过一台linux ssh远程其他linux服务器时,不要输入密码,可以自动登入.提高远程效率,不用记忆各台服务器的密码. 工具/原料 ssh,ssh-keygen,scp 方法/步骤 ...
- ArcGIS10.1的安装问题
注:必须用3个带0的文件夹里面的东西安装 1.先装Pre-release_license_manager ,然后停掉. 2.然后安装0Desktop/ArcGIS_Desktop, 3.打开0Ke ...
- 安装express
就目前来说安装express需要走几个步骤,要不就会出现在检查版本的时候就会出现,expres不是内部的命令或者是这种 安装的步骤: 1. 先是输入npm install -g express-gen ...
- 在vue-cli中引入外部插件
一.可以用npm下载的 现在以jquery为例子: 1 先在package.json中的dependencies中写入“jquery”:“^3.2.1”(jquery版本) 2 在npm中搜索jque ...
- 【洛谷4149】[IOI2011] Race(点分治)
点此看题面 大致题意: 给你一棵树,问长度为\(K\)的路径至少由几条边构成. 点分治 这题应该比较显然是点分治. 主要思路 与常见的点分治套路一样,由于\(K≤1000000\),因此我们可以考虑开 ...