python讀寫配置文件ConfigParser

  1. # -* - coding: UTF-8 -* -  ide

  2. import ConfigParser  spa

  3. #生成config對象  orm

  4. conf = ConfigParser.ConfigParser()  對象

  5. #用config對象讀取配置文件  get

  6. conf.read("test.cfg")  string

  7. #以列表形式返回全部的section  it

  8. sections = conf.sections()  io

  9. print 'sections:', sections         #sections: ['sec_b', 'sec_a']  class

  10. #獲得指定section的全部option  test

  11. options = conf.options("sec_a")  

  12. print 'options:', options           #options: ['a_key1', 'a_key2']  

  13. #獲得指定section的全部鍵值對  

  14. kvs = conf.items("sec_a")  

  15. print 'sec_a:', kvs                 #sec_a: [('a_key1', '20'), ('a_key2', '10')]  

  16. #指定section,option讀取值  

  17. str_val = conf.get("sec_a""a_key1")  

  18. int_val = conf.getint("sec_a""a_key2")  

  19.   

  20. print "value for sec_a's a_key1:", str_val   #value for sec_a's a_key1: 20  

  21. print "value for sec_a's a_key2:", int_val   #value for sec_a's a_key2: 10  

  22.   

  23. #寫配置文件  

  24. #更新指定section,option的值  

  25. conf.set("sec_b""b_key3""new-$r")  

  26. #寫入指定section增長新option和值  

  27. conf.set("sec_b""b_newkey""new-value")  

  28. #增長新的section  

  29. conf.add_section('a_new_section')  

  30. conf.set('a_new_section''new_key''new_value')  

  31. #寫回配置文件  

  32. conf.write(open("test.cfg""w"))  

相關文章
相關標籤/搜索