python2.7中ConfigParser模块对配置文件的读写 *** 作。
一、ConfigParser模块的函数
1.读取
read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型
2.写入
add_section(section) 添加一个新的section
set( section, option, value) 对section中的option进行设置
conf.write() 写入
二、ConfigParser代码示例
1.配置文件
如果没有配置文件会报错:ConfigParser.NoSectionError: No section
[db1] conn = localhost port = 3306 user = root password = 123456 dbname = test [db2] conn = localhost port = 3306 user = root password = 123456 dbname = test1
2.读取与写入代码
#/usr/bin/python #-*- coding:utf-8 -*- import ConfigParser #生成conf对象 conf = ConfigParser.ConfigParser() #载入配置文件 conf.read('conf.ini') #===读取=== #列出所有section print conf.sections() #输出 ['db1', 'db2'] #列出指定section中的option print conf.options('db1') #输出 ['conn', 'port', 'user', 'password', 'dbname'] #列出指定区的所有键值 print conf.items('db1') #输出 [('conn', 'localhost'), ('port', '3306'), ('user', 'root'), ('password', '123456'), ('dbname', 'test')] #获取指定section中指定键的值 print conf.get('db1','conn') #输出 localhost #===写入=== #增加section conf.add_section('db3') #设置增加section的option值 conf.set('db3','conn','127.0.0.1') #更新指定section的option值 conf.set('db3','conn','localhost') #保存到配置文件 conf.write(open('conf.ini','w'))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)