简介
ConfigParser是用来读取配置文件的模块。基本方法
-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() 函数
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行添加或设置- 配置文件格式
[section1]
option1 = value1
[section2]
option2 = value2
- 举例
配置文件 config.ini
# database
[db]
host = 127.0.0.1
port = 3306
user = root
passwd = root
# ssh
[ssh]
host = 172.16.1.10
user = huqin
pass = 12345
读取配置文件
#author : huqin
#conding : utf-8
import ConfigParser
#初始化并加载配置文件
config = ConfigParser.ConfigParser()
config.read('config.ini')
#获取所有sections
print config.sections()
#输出 ['db', 'ssh']
#获取指定section的options
print config.options('db')
#输出 ['host','port','user','passwd']
#获取知道option的value
print config.get('db', 'user')
#输出 root