您的位置:首页 > 编程语言 > Python开发

Python配置工具类ConfigParser使用

2015-03-26 15:19 302 查看
ConfigParser模块定义了类ConfigParser,用于实现配置文件解释器。该模块ConfigParser在Python3中,已更名为configparser。

一,函数介绍

1.读取配置文件

read(filename) 直接读取ini文件内容readfp(fp[, filename])从文件或fp(值使用该对象的readline()方法)中的似文件类读取并解析配置数据,如果filename被省略,fp有一个name属性,该属性用于获取filename;默认是“<???>”。sections() 得到所有的section,并以列表的形式返回options(section) 得到指定section的所有optionitems(section) 得到指定section的所有键值对get(section,option) 得到指定section中option的值,返回为string类型getint(section, option)
得到指定section下的option的值,作为Int类型返回的方便方法。

getfloat(section, option)
得到section下的option值,作为float类型返回的方法方法。

getboolean(section, option)
得到section下的option值,作为布尔类型返回的方法方法。注意可接受的option的true值有“1”,“yes”,“true”及“on”,可接受的false值有“0”,“no”,“false”,“off”。字符串值不检测大小写,其他值会抛出ValueError异常。

has_section(section)
判断给定的section名在配置文件中是否存在,DEFAULT section不包括。
optionxform(option)
将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;子类可能重写该方法或客户端代码可能将该方法作为实例的属性,以此来影响它的行为。将此用于str(),例如,会使option名称大小写敏感。


2.写入配置文件

add_section(section)
为实例添加一个section,如果给定的section名已经存在,将抛出DuplicateSectionError异常。

set( section, option, value)

如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增。remove_option(section, option)
从指定section中删除指定option,如果section不存在,抛出NoSectionError异常;如果option存在,则删除,并返回True;否则返回false。1.6版本新增。

remove_section(section)
从配置文件中删除指定的section,如果section确实存在,返回true,否则返回false。

write(fileobject) 将配置表示写入指定文件类,该表示以后可以通过调用read()来解析,1.6版本新增。

二,代码示例

ini.cfg[src_mysql]
host=192.168.190.922
port =3306
user=test
passwd=123456
connect_timeout=120
limit=10000
db=bb
charset=uft8
[dsc_mysql]
host=192.168.190.922
port =3306
user=test
passwd=123456
connect_timeout=120
db=aa
charset=uft8from ConfigParser import ConfigParser

class ConfigUtils(object):
def __init__(self,fileName):
super(ConfigUtils, self).__init__()
try:
self.config = ConfigParser()
self.config.read(fileName)
except IOError,e:
print traceback.print_exc()

cu = ConfigUtils('ini.cfg')

#打印所有的section
print cu.config.sections()
>>>['src_mysql', 'dsc_mysql']

#删除指定section
cu.config.remove_section('src_mysql')
>>>True

#打印所有的section
cu.config.sections()
>>>['dsc_mysql']

#打印对应section的所有items键值对
cu.config.items('dsc_mysql')
>>>[('passwd', 'mytest'), ('charset', 'uft8'), ('db', 'anlitest'), ('port', '3306'), ('host', '192.168.10.222'), ('user', 'optusr'), ('connect_timeout', '120')]

#写配置文件
#增加新的section
cu.config.add_section('src_mysql')
#写入指定section增加新option和值
cu.config.set("src_mysql", "passwd", "new-value")
cu.config.set("src_mysql", "charset", "new_value")
cu.config.set("src_mysql", "db", "new-value")
cu.config.set("src_mysql", "port", "new_value")
cu.config.set("src_mysql", "host", "new_value")
cu.config.set("src_mysql", "user", "new_value")
cu.config.set("src_mysql", "connect_timeout", "new_value")
#写回配置文件
cu.config.write(open("test.cfg", "w"))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: