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

Python 解析配置模块之ConfigParser详解

2016-03-25 11:07 751 查看
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类型,还有相应的getboolean()和getfloat() 函数。

2.基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

例子:
test.txt
[sec_a]
a_key1 = 20
a_key2 = 10

[sec_b]
b_key1 = b_value2
b_key2 = 120
b_key3 = $r
b_key4 = 127.0.0.1

#1、基本的读取配置文件
import ConfigParser

cf = ConfigParser.ConfigParser()
cf.read('d:/test/test.txt') # 读取文件路径

sc = cf.sections() #得到所有的section,并以列表形式返回
print 'sections:',sc

op = cf.options('sec_b') #得到section中所有的option
print 'options:',op

it = cf.items('sec_a') # 得到section中所有的键值对
print 'items:',it

str_val = cf.get('sec_a','a_key1') # 得到section中option的值,string类型
print "a_key1 =",str_val

int_val = cf.getint('sec_a','a_key2') # 得到section中option的值,int类型
print "a_key2 =",int_val

str_val = cf.get('sec_b','b_key1') # 得到section中option的值,string类型print "b_key1 =",str_val
int_val = cf.getint('sec_b','b_key2') # 得到section中option的值,int类型print "b_key2 =",int_val

#2.基本的写入配置文件
cf.set('sec_b','b_key3','new_#r') # 对section中的iptions中的值进行设置

cf.set('sec_a','a_newkey','new_value') # 对section中的iptions和options中的值进行设置

cf.add_section('sec_c') # 添加一个新的section

cf.set('sec_c','c_key1','new_123') #在section写入新的键值对

cf.write(open('d:/test/test.txt','w')) # 打开文档并把要数据写进文档中
注:一定要加'w',不加的话,无法将信息写入到指定的文件中。

1、基本的读取配置文件,输出结果:
sections: ['sec_a', 'sec_b']
options: ['b_key1', 'b_key2', 'b_key3', 'b_key4']
items: [('a_key1', '20'), ('a_key2', '10')]
a_key1 = 20
a_key2 = 10
b_key1 = b_value2
b_key2 = 120

2.基本的写入配置文件,输出结果:

[sec_a] a_key1 = 20 a_key2 = 10 a_newkey = new_value [sec_b] b_key1 = b_value2 b_key2 = 120 b_key3 = new_#r b_key4 = 127.0.0.1
[sec_c]
c_key1 = new_123

附件:http://down.51cto.com/data/2367497
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ConfigParser详解