When developing in Python, databases or other things that require dynamic configuration are often used. It would be troublesome to hard-code them and change them every time. Python has its own module ConfigParser for reading configuration files, which is very convenient to use.
ini file
ini configuration file format:
Read configuration file:
import ConfigParser conf = ConfigParser.ConfigParser() conf.read('dbconf.ini') # 文件路径 name = conf.get("section1", "name") # 获取指定section 的option值 print name sex = conf.get("section1", "sex") # 获取section1 的sex值 print age
Output:
jhao male
Write configuration file:
import ConfigParser conf = ConfigParser.ConfigParser() conf.read('dbconf.ini') conf.set("section1", "name", "jhao104") # 修改指定section 的option conf.set("section1", "age", "21") # 增加指定section 的option conf.add_section("section3") # 增加section conf.set("section3", "site", "oschina.net") # 给新增的section 写入option conf.write(open('dbconf.ini', 'w'))
Output: