ConfigParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:
import ConfigParser
import string, os, sys
cf = ConfigParser.ConfigParser()
cf.read( " test.conf " )
# 返回所有的section
s = cf.sections()
print ' section: ' , s
o = cf.options( " db " )
print ' options: ' , o
v = cf.items( " db " )
print ' db: ' , v
print ' - ' * 60
# 可以按照类型读取出来
db_host = cf.get( " db " , " db_host " )
db_port = cf.getint( " db " , " db_port " )
db_user = cf.get( " db " , " db_user " )
db_pass = cf.get( " db " , " db_pass " )
# 返回的是整型的
threads = cf.getint( " concurrent " , " thread " )
processors = cf.getint( " concurrent " , " processor " )
print " db_host: " , db_host
print " db_port: " , db_port
print " db_user: " , db_user
print " db_pass: " , db_pass
print " thread: " , threads
print " processor: " , processors
# 修改一个值,再写回去
cf.set( " db " , " db_pass " , " zhaowei " )
cf.write(open(" test.conf " , " w " ))
import ConfigParser
config = ConfigParser.ConfigParser()
# set a number of parameters
config.add_section("book")
config.set("book", "title", "the python standard library")
config.set("book", "author", "fredrik lundh")
config.add_section("ematter")
config.set("ematter", "pages", 250)
# write to file
config.write(open('1.ini', "w"))
修改也可以
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('1.ini')
a = config.add_section("md5")
config.set("md5", "value", "1234")
config.write(open('1.ini', "r+")) #可以把r+改成其他方式,看看结果:)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('1.ini')
config.set("md5", "value", "kingsoft") #这样md5就从1234变成kingsoft了
config.write(open('1.ini', "r+"))