Python Configparser模块读取、写入配置文件

写代码中需要用到读取配置,最近在写python,记录一下。

如下,假设有这样的配置。

[db]    
db_host=127.0.0.1 
db_port=3306   
db_user=root   
db_pass= 
[concurrent]    
thread=200   
processor=400

可以使用ConfigParser模块来读取、写入配置。

 1 #coding=utf-8
 2 import ConfigParser
 3 import sys 
 4 
 5 cf = ConfigParser.ConfigParser()    
 6 cf.read(sys.argv[1])   
 7 
 8 # 返回所有的section
 9 s = cf.sections()
10 print s #['db', 'concurrent']
11 
12 # 返回db下面所有的options
13 db_options = cf.options("db")
14 print db_options    #['db_host', 'db_port', 'db_user', 'db_pass']
15 
16 print cf.get("db", "db_host")   #127.0.0.1
17 print cf.getint("db", "db_port")    #3306
18 
19 # 修改一个值, 并写回去
20 cf.set("db", "db_host", "losthost")
21 # 添加一个section
22 cf.add_section("new_concurrent")
23 cf.set("new_concurrent", "thread", "500")
24 
25 ##删除一个section
26 cf.remove_section('concurrent')
27 cf.write(open("test_new.conf", "w"))
28 #cf.write(open(sys.argv[1], "w"))

完.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值