当前位置:Gxlcms > Python > Python使用自带的ConfigParser模块读写ini配置文件

Python使用自带的ConfigParser模块读写ini配置文件

时间:2021-07-01 10:21:17 帮助过:83人阅读

在用Python做开发的时候经常会用到数据库或者其他需要动态配置的东西,硬编码在里面每次去改会很麻烦。Python自带有读取配置文件的模块ConfigParser,使用起来非常方便。

ini文件
ini配置文件格式:

2016626174140238.png (273×249)

读取配置文件:

  1. import ConfigParser
  2. conf = ConfigParser.ConfigParser()
  3. conf.read('dbconf.ini') # 文件路径
  4. name = conf.get("section1", "name") # 获取指定section 的option值
  5. print name
  6. sex = conf.get("section1", "sex") # 获取section1 的sex值
  7. print age

输出:

  1. jhao
  2. male


写入配置文件:

  1. import ConfigParser
  2. conf = ConfigParser.ConfigParser()
  3. conf.read('dbconf.ini')
  4. conf.set("section1", "name", "jhao104") # 修改指定section 的option
  5. conf.set("section1", "age", "21") # 增加指定section 的option
  6. conf.add_section("section3") # 增加section
  7. conf.set("section3", "site", "oschina.net") # 给新增的section 写入option
  8. conf.write(open('dbconf.ini', 'w'))

输出:

2016626174242767.png (288×355)

人气教程排行