python总结——处理配置文件(ConfigParser)

2016-05-03  橙子 

python处理ConfigParser

 

使用ConfigParser模块读写ini文件 (转载)

ConfigParserPython 的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、 SafeConfigParser。模块所解析的ini配置文件是由多个section构成,每个section名用中括号‘[]’包含,每个 section下可有多个配置项类似于key-value形式,例如:

ConfigParser模块以ConfigParser类为例,其操作基本分为三类:1)初始化;2)读取配置;3)写入配置。

1. ConfigParser 初始化

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

cf = ConfigParser.ConfigParser()

cf.read("配置文件名")

2. 基本的读取配置文件

-read(filename) 直接读取ini文件内容

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

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

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

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

3.基本的写入配置文件

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

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

-write(strout) 将对configparser类的修改写入

例子:

import ConfigParser

'''

[mysql]

ip=127.0.0.1

port=8000

username=zhangsan

passwd=123456

'''

 

cf=ConfigParser.ConfigParser()

cf.read('E:/config.ini')

sections=cf.sections()

options=cf.options('mysql')

items=cf.items('mysql')

ip=cf.get('mysql', 'ip')

print sections,options,items,ip

439°/4395 人阅读/0 条评论 发表评论

登录 后发表评论