python中读取配置文件ConfigParser

时间:2021-06-06 22:23:45

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。
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

_______________________________________________________________________________________________________________________________
#!/usr/bin/python
#coding:utf-8

import ConfigParser
import string,os,sys

cf = ConfigParser.ConfigParser()
#读取配置文件
cf.read("test.conf")

#返回section,即[]中的内容
s = cf.sections()
print 'section:', s

#返回db section中的选项
o = cf.options("db")
print 'options:',o
#以列表形式返回db section中选项和值
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","test")
cf.write(open("test.conf","w"))