Python 解析配置文件 (ConfigParser)模块
配置文件可以为(.ini或者.conf)
内容形式举例:
[mysql] #[mysql] 为section部分
host = 127.0.0.1 #host,user为其配置项
user = root
passwd = 1234
db = mysql
[concurrent]
threads = thread1
利用ConfigParser模块解析文件
程序举例:
# /usr/bin/python
# encoding: utf-8
import ConfigParser
import string, os, sys
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
# 返回所有的section
s = cf.sections()
print 'section:', s
o = cf.options("mysql")
print 'options:', o
v = cf.items("mysql")
print 'mysql:', v
#可以按照类型读取出来
db_host = cf.get("mysql", "host")
db_user = cf.getint("mysql", "user")
db_passwd = cf.get("mysql", "passwd")
db_sql = cf.get("mysql", "db")
# 返回的是整型的
threads = cf.getint("concurrent", "thread")
print "db_host:", db_host
print "db_user:", db_port
print "db_passwd:", db_user
print "db_sql:", db_pass
print "thread:", threads
#修改一个值,再写回去
cf.set("db", "passwd", "rose")
cf.write(open("test.conf", "w"))