python标准库:Configparser模块
配置文件test.conf
1 [section1] 2 name = tank 3 age = 28 4 [section2] 5 ip = 192.168.1.1 6 port = 8080
示例
1 # -* - coding: UTF-8 -* - 2 import ConfigParser 3 conf = ConfigParser.ConfigParser() 4 conf.read("c:\\test.conf") 5 # 获取指定的section, 指定的option的值 6 name = conf.get("section1", "name") 7 print(name) 8 age = conf.get("section1", "age") 9 print age 10 #获取所有的section 11 sections = conf.sections() 12 print sections 13 #写配置文件 14 # 更新指定section, option的值 15 conf.set("section2", "port", "8081") 16 # 写入指定section, 增加新option的值 17 conf.set("section2", "IEPort", "80") 18 # 添加新的 section 19 conf.add_section("new_section") 20 conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao") 21 # 写回配置文件 22 conf.write(open("c:\\test.conf","w"))