1. 简介
python 中的 configparser 是用来解析 .ini | .cfg
格式的配置文件的一个模块。这种格式的文件一般用来储存项目对各种模块的配置,例如:数据库,全局参数等。
简单说下 .ini | .cfg
文件的格式
- 键值对可用
=
或者:
进行分隔 section
的名字是区分大小写的,而key
的名字是不区分大小写的- 键值对中头部和尾部的空白符会被去掉
- 值可以为多行
- 配置文件可以包含注释,注释以
#
或者;
为前缀
当然上述格式可以在 configparser
模块创建 .ini
文件的时候重载为自己设计的格式,上述格式一般为通用 | 默认使用的格式。
举个🌰
demo.txt
[DEFAULT]
type = animal
age = 3
[cat]
name = tom
[dog]
Port = Emily
2. 参数
class configparser.ConfigParser(
defaults=None,
dict_type=dict,
allow_no_value=False,
delimiters=('=', ':'),
comment_prefixes=('#', ';'),
inline_comment_prefixes=None,
strict=True,
empty_lines_in_values=True,
default_section=configparser.DEFAULTSECT,
interpolation=BasicInterpolation(),
converters={
})
defaults
当给定 defaults 时,它会被初始化为包含固定默认值的字典。
import configparser
default = {
'type': 'animal',
'age': '3'
}
config = configparser.ConfigParser(defaults=default)
print(config.get('DEFAULT', 'type'))
# 输出
animal
dict_type
当给定 dict_type 时,它将被用来创建包含节点、节点中的选项以及默认值的字典
parser = configparser.ConfigParser()
parser.read_dict({
'section1': {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'},
'section2': {
'keyA': 'valueA',
'keyB': 'valueB',
'keyC': 'valueC'},
'section3': {
'foo': 'x',
'bar': 'y',
'baz': '