典型的配置文件包含一到多个章节(section),每个章节下可以包含一个到多个的选项(option)。如下就是一个典型的MySQL配置文件:
[client]
port = 3306
user = mysql
password = mysql
host = 127.0.0.1
[mysqld]
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
Python 标准库的configparser模块用以接卸配置文件。
ConfigParse模块包含一个ConfigParser类,一个ConfigParser对象,可同时解析多个配置文件。
import ConfigParser
##ConfigParser方法
###读取配置
sections //返回一个包含所有章节的列表
has_section //判断章节是否存在
items // 元组的形式返回所有选项
options // 返回一个包含章节下所有选项的列表
has_option // 判断某个选项是否存在
get getboolean getint getfloat // 获取选项的值
###修改配置
remove_section // 删除一个章节
add_section // 添加一个章节
remote_option // 删除一个选项
set // 添加一个选项
write // 将ConfigParser对象中的数据保存到文件中
cf = ConfigParser.ConfigParser(allow_no_value=True) //allow_no_value 默认为false,表示允许选项没有值,选项存在就表示取值为真,不存在取值为假
In [4]: cf.read('my.cnf')
Out[4]: ['my.cnf']
In [5]: cf.sections()
Out[5]: ['client', 'mysqld']
In [6]: cf.has_section('client')
Out[6]: True
In [7]: cf.options("client")
Out[7]: ['port', 'user', 'password', 'host']
In [8]: cf.has_option("client", "user")
Out[8]: True
In [9]: cf.get("client","host")
Out[9]: '127.0.0.1'
In [10]: cf.getint("client" ,"port")
Out[10]: 3306
In [11]: cf.remove_section('client')
Out[11]: True
In [12]: cf.add_section('mysql')
In [13]: cf.set('mysql','host','127.0.0.1')
In [14]: cf.set('mysql','port',3306)
In [15]: cf.write(open('my_copy.cnf', 'w'))