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
=  cf.sections()
print   ' section: ' , s

=  cf.options( " db " )
print   ' options: ' , o

=  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 " ))


 

From http://www.pythonid.com/html/fenleiwenzhang/text/20070704/28.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值