python模块之ConfigParser: 用python解析配置文件
http://groups.google.com/group/python-cn/browse_thread/thread/fdbb2d3e2c59dcf4/4ba9c9557a500d29?hl=zh-CN#4ba9c9557a500d29
> def dump_config(fn, dict):
>   fout = file(fn, 'wb')
>   for k, v in dict.items():
>     fout.write('%s=%s\n' % (k, v))
>   fout.close()

python模块之ConfigParser: 用python解析配置文件
在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在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

假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:

#-*- encoding: gb2312 -*-
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"))

原文地址

The ConfigParser module

This module reads configuration files.

The files should be written in a format similar to Windows INI files. The file contains one or more sections, separated by section names written in brackets. Each section can contain one or more configuration items.

Here’s an example:

[book]
title: The Python Standard Library
author: Fredrik Lundh
email: fredrik@pythonware.com
version: 2.0-001115

[ematter]
pages: 250

[hardcopy]
pages: 350 Example: Using the ConfigParser module # File: configparser-example-1.py

import ConfigParser
import string

config = ConfigParser.ConfigParser()

config.read("samples/sample.ini")

# print summary
print
print string.upper(config.get("book", "title"))
print "by", config.get("book", "author"),
print "(" + config.get("book", "email") + ")"
print
print config.get("ematter", "pages"), "pages"
print

# dump entire config file
for section in config.sections():
print section
for option in config.options(section):
print " ", option, "=", config.get(section, option) THE PYTHON STANDARD LIBRARY
by Fredrik Lundh (fredrik@pythonware.com)

250 pages

book
title = Python Standard Library
email = fredrik@pythonware.com
author = Fredrik Lundh
version = 2.0-010504
__name__ = book
ematter
__name__ = ematter
pages = 250
hardcopy
__name__ = hardcopy
pages = 300

In Python 2.0, this module also allows you to write configuration data to a file.

Example: Using the ConfigParser module to write configuration data # File: configparser-example-2.py

import ConfigParser
import sys

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 screen
config.write(sys.stdout) [book]
title = the python standard library
author = fredrik lundh

[ematter]
pages = 250 [comment on/vote for this article]

Comment:

Why would I use configuration files if I can use a simple Python-like file ?

Posted by Marshall (2007-01-10)

Comment:

Well, using a python like a file for Config file is actually a nifty idea. I would see this as a credit to the beauty of Python language. But remember the users who should not be disturbed by a python file and a configuration file and who have got used to config file in .ini format and shell config files. For them and standard purposes, configfile is best and ConfigParser comes handy. Moreover, the format being RFC822 standard, you will have the flexiblity to use any other program which understands this as well. Hope this helps. Thanks,

Posted by Senthil (2007-02-02)

Comment:

With Python-like ini files you may also run into security issues: as the user can edit those files, he can use whatever python commands he likes, including harmful ones...

Posted by Boon (2007-02-28)

Comment:

Marshall, you obviously have not worked in a production environment with legacy business systems. There are untold numbers of legacy systems out there which require monitoring, work-arounds, updates, enhancements, etc. You may not need to create a configuration file for new development, but one day you will run into a legacy system that will require this module. Peace out, yo.

Posted by Anonymous Coward (2007-04-11)