configparser 简介
configparser是Pyhton标准库中用来解析配置文件的模块,并且内置方法和字典非常接近。Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能。
配置文件的格式如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Tom
[topsecret.com]
Port: 50022
ForwardX11: no
[ ]
包含的为section,section下面为类似于key-value的配置内容; configparser默认支持 =
和:
两种分隔。
configparser 常用方法
初始化实例
使用 configparser 首先需要初始化实例,并读取配置文件:
>>> import configparser
>>> config = configparser.ConfigParser() # 注意大小写
>>> config.read("config.ini") # 配置文件的路径
["config.ini"]
或者可以直接读字典
>>> parser = configparser.ConfigParser()
>>> parser.read_dict({
'section1': {
'key1': 'value1',
... 'key2': 'value2',
... 'key3': 'value3'}