ConfigParser模块解析配置文件

  1. 解析配置文件很常见,Python官方的库ConfigParser就自带了这功能。
  2. 配置文件由多个section构成,每个section下面有多个配置项,配置项的格式为:key=value

假设有一个配置文件为config.conf,格式如下,有两个section,我们来利用ConfigParser模块对其做解析:

[db]
db_host=localhost
db_port=3306
db_user=root
db_pass=toor
[concurrent]
thread=10
processor=20

解析的Python代码如下,比较简单,10分钟就能学完。

import ConfigParser

conf = ConfigParser.ConfigParser()
conf.read("/Users/Heros/config.conf")
all_sections = conf.sections()                       # 返回['db', 'concurrent']
db_options = conf.options("db")                      # 返回['db_host', 'db_port', 'db_user', 'db_pass']
db_values = conf.items("db")                         # 返回[('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]
db_host = conf.get("db", "db_host")                  # 返回127.0.0.1
db_port = conf.getint("db", "db_port")               # 返回3306

conf.set("db", "db_pass", "passw0rd")                # 修改值
conf.write(open("/Users/Heros/config.conf", "w"))    # 将修改值写回去

Comments !