轉載自:http://hi.baidu.com/myitlyj/blog/item/25586bd7088ba3dba044df6b.html<br />在程式中使用設定檔來靈活的配置一些參數是一件很常見的事情,設定檔的解析並不複雜,在python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser,這裡簡單的做一些介紹。<br /> ConfigParser解析的設定檔的格式比較象ini的設定檔格式,就是檔案中由多個section構成,每個section下又有多個配置項,比如:<br />[db]<br />db_host=127.0.0.1<br />db_port=3306<br />db_user=root<br />db_pass=password<br />[concurrent]<br />thread=10<br />processor=20<br /> 假設上面的設定檔的名字為test.conf。裡麵包含兩個section,一個是db, 另一個是concurrent, db裡面還包含有4項,concurrent裡面有兩項。這裡來做做解析:<br />#-*- encoding: gb2312 -*-<br />import ConfigParser<br />import string, os, sys<br />cf = ConfigParser.ConfigParser()<br />cf.read("test.conf")<br /># 返回所有的section<br />s = cf.sections()<br />print 'section:', s<br />o = cf.options("db")<br />print 'options:', o<br />v = cf.items("db")<br />print 'db:', v<br />print '-'*60<br />#可以按照類型讀取出來<br />db_host = cf.get("db", "db_host")<br />db_port = cf.getint("db", "db_port")<br />db_user = cf.get("db", "db_user")<br />db_pass = cf.get("db", "db_pass")<br /># 返回的是整型的<br />threads = cf.getint("concurrent", "thread")<br />processors = cf.getint("concurrent", "processor")<br />print "db_host:", db_host<br />print "db_port:", db_port<br />print "db_user:", db_user<br />print "db_pass:", db_pass<br />print "thread:", threads<br />print "processor:", processors<br />#修改一個值,再寫回去<br />cf.set("db", "db_pass", "zhaowei")<br />cf.write(open("test.conf", "w"))<br />