Python 解析配置文件 (ConfigParser)模块

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")) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值