解析配置文件ConfigParser模块

一.ConfigParser简介

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

 1 [mongoDb] #-------->section
 2 userName=dsg
 3 passWord=dsg
 4 dataBase=promo
 5 tableName=trace
 6 mongodb_ip_port=127.0.0.1:3717
 7 
 8 [filePath]#-------->section
9 incoming=/mnt/data/share/ingest/incoming/mongo

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

二、ConfigParser 初始工作

使用ConfigParser 首选需要初始化实例,并读取配置文件:

1 import ConfigParser
2 cf = ConfigParser.ConfigParser()#生成一个实例
3 cf.read("配置文件名") #读取配置文件

三、ConfigParser 基本操作

1.基本的读取配置文件

-read(filename) 直接读取.conf文件内容。

-sections() 得到所有的section,并以列表的形式返回。

['mongoDb', 'filePath']

-options(section) 得到该section的所有option,并以列表的形式返回。

['username', 'password', 'database', 'tablename', 'mongodb_ip_port']

-items(section) 得到该section的所有键值对,以列表的形式返回

[('username', 'dsg'), ('password', '123'), ('database', 'promo'), ('tablename', 'trace'), ('mongodb_ip_port', '127.0.0.1:3717')]

-get(section,option) 得到section中option的值,返回为string类型

123 <type 'str'>

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。注意类型不对会报错。

123 <type 'int'>

2.基本的写入配置文件

-add_section(section) 添加一个新的section

conf.add_section('abcd')

-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

1 conf.set('abcd','haha','dsadasdasdada') #添加
2 conf.set('mongoDb','passWord','2222222')#修改

注意:没有write()操作是不生效的。

conf.write(open('F:\clientconf.conf','w')

四、具体使用示例

1.获取所有的sections

也就是将配置文件中所有“[ ]”读取到列表中:

1 sectionsList=conf.sections()
2 print 'sectionsList:',sectionsList
3 #输出结果为
4 ['mongoDb', 'filePath']

2.获取指定sections的opention

即将配置文件某个section 内key 读取到列表中:

1 1 optionsList=conf.options('mongoDb')
2 2 print 'optionsList:',optionsList
3 3 #输出结果
4 4 ['username', 'password', 'database', 'tablename', 'mongodb_ip_port']

3.获取指定的sections的配置信息

获取指定节点下所有的键值对

1 mongoDb=conf.items('mongoDb')
2 print 'mongoDb=',mongoDb
3 #输出结果是
4 [('username', 'dsg'), ('password', '2222222'), ('database', 'promo'), ('tablename', 'trace'), ('mongodb_ip_port', '127.0.01:3717')]

4.按照类型读取指定的sections的opention信息

 1 print 'str=',conf.get('mongoDb','passWord')
 2 print 'strType=',type(conf.get('mongoDb','passWord'))#
 3 
 4 print 'int=',conf.getint('mongoDb','passWord') 
 5 print 'intType=',type(conf.getint('mongoDb','passWord'))#注意:类型不对,会报错误!
 6 #输出结果:
 7 2222222
 8 <type 'str'>
 9 2222222
10 <type 'int'>

5.添加opention和设置某个opention的值

1 conf.add_section('abcd')#添加section
2 conf.set('abcd','haha','dsadasdasdada')#添加opentions
3 conf.set('mongoDb','passWord','2222222')#修改 opentions
4 conf.write(open('F:\clientconf.conf','w'))#只有写入才有效

6.删除section或者opention

1 cf.remove_option('liuqing','int')
2 cf.remove_section('liuqing')
3 cf.write(open("test.conf", "w")

7.检查是否存在

1 has_sec =  obj.has_section("mysql1") # false
2 print(has_sec)
原文地址:https://www.cnblogs.com/chushiyaoyue/p/5356878.html