Python ConfigParser模块常用方法示例

 
 
 
  1.  在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。  
  2.   
  3. Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:  
  4.   
  5. [db]    
  6. db_host=192.168.1.1   
  7. db_port=3306   
  8. db_user=root   
  9. db_pass=password   
  10. [concurrent]    
  11. thread=200   
  12. processor=400   
  13. 假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:  
  14.   
  15. #-*- encoding: gb2312 -*-    
  16. import ConfigParser,string,os,sys    
  17. cf = ConfigParser.ConfigParser()    
  18. cf.read("test.conf")   
  19.   
  20. # 返回所有的section    
  21. s = cf.sections()    
  22. print 'section:', s    
  23. o = cf.options("db")    
  24. print 'options:', o    
  25. v = cf.items("db")    
  26. print 'db:', v    
  27. print '-'*60    
  28.   
  29. #可以按照类型读取出来  
  30. db_host = cf.get("db""db_host")    
  31. db_port = cf.getint("db""db_port")    
  32. db_user = cf.get("db""db_user")    
  33. db_pass = cf.get("db""db_pass")   
  34.   
  35. # 返回的是整型的    
  36. threads = cf.getint("concurrent""thread")    
  37. processors = cf.getint("concurrent""processor")    
  38. print "db_host:", db_host    
  39. print "db_port:", db_port    
  40. print "db_user:", db_user    
  41. print "db_pass:", db_pass    
  42. print "thread:", threads    
  43. print "processor:", processors   
  44.   
  45. #修改一个值,再写回去    
  46. cf.set("db""db_pass""zhaowei")    
  47. cf.write(open("test.conf""w"))   
  48.   
  49. #添加一个section。(同样要写回)  
  50. cf.add_section('liuqing')  
  51. cf.set('liuqing''int''15')  
  52. cf.set('liuqing''bool''true')  
  53. cf.set('liuqing''float''3.1415')  
  54. cf.set('liuqing''baz''fun')  
  55. cf.set('liuqing''bar''Python')  
  56. cf.set('liuqing''foo''%(bar)s is %(baz)s!')  
  57. cf.write(open("test.conf""w"))  
  58.   
  59. #移除section 或者option 。(只要进行了修改就要写回的哦)  
  60. cf.remove_option('liuqing','int')  
  61. cf.remove_section('liuqing')  
  62. cf.write(open("test.conf""w"))  
  63.   
  64. 以上就是对Python ConfigParser模块的相关应用方法的介绍,当然,这个模块还有许多其他的用法,有兴趣的可以去官方网站看看:http://docs.python.org/2/library/configparser.html。  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值