Python的配置文件解析器configparser

此模块提供ConfigParser实现基本配置语言的类,该语言提供类似于Microsoft Windows INI文件中的结构。您可以使用它来编写可由最终用户轻松定制的Python程序。

ini配置文件介绍

根据官方文档得知,ini文件的定义主要有以下几点:

  • 配置文件由一个或多个[section]组成,每个[section]代表一组配置文件的集合
  • Key与Value之间可用=或者:分隔
  • Key与Value中允许出现空格
  • [section]的名称区分大小写,Key不区分
  • 可以省略Value,省略等号和Value表示没有值,如果只省略Value,则表示值为空字符串
  • Value可以跨域多行,但是跨行后的数据值需要进行一定的缩进
  • 配置文件可以包括注释,以#或者;开头的

下面是官方的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?

接下来我们就以官方文档的例子来实现配置文件的读取与写入。

读取配置文件

1
2
3
4
5
import configparser

config = configparser.ConfigParser(interpolation=configparser.BasicInterpolation())
config.read(r'./test.ini')
print(config['Simple Values'])

此时会打印如下内容:

1
<Section: Simple Values>

[Simple Values]这种形式的被称为Section
如果我们要打印所有的Section,则只需要如下代码即可

1
print(config.sections())

此时会输出如下内容:

1
['Simple Values', 'All Values Are Strings', 'Multiline Values', 'No Values', 'You can use comments']

如果我们要打印Simple Values这个Section下的所有key,只需要如下代码即可:

1
print(config.options('Simple Values'))

此时会输出如下内容:

1
['key', 'spaces in keys', 'spaces in values', 'spaces around the delimiter', 'you can also use']

如果要获取Simple Values下所有的键值对,则需要如下代码:

1
print(config.items('Simple Values'))

此时会输入如下内容:

1
[('key', 'value'), ('spaces in keys', 'allowed'), ('spaces in values', 'allowed as well'), ('spaces around the delimiter', 'obviously'), ('you can also use', 'to delimit keys from values')]

如果要获取Simple Valueskey的值,则需要如下代码:

1
2
3
print(config['Simple Values']['key'])
# or
print(config.get('Simple Values', 'key'))

此时会输入如下内容:

1
value

如果要获取指定类型的值,则需要如下代码:

1
2
print(config.getint('All Values Are Strings', 'values like this'))
print(type(config.getint('All Values Are Strings', 'values like this')))

此时会输出如下内容:

1
2
1000000
<class 'int'>

类似的还有config.getboolean()config.getfloat(),同时需要注意getboolean()方法能判断True/False的值有:yes/no, on/off, true/false1/0

写入配置

关于写如配置的方法,有如下四种方式可以实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
config1 = configparser.ConfigParser()
# 直接写入字典数据
config1['Test Write First'] = {'name': 'cco',
'age': '20'}
# 可以直接写入指定的key和value
config1['Test Write Second'] = {}
config1['Test Write Second']['wight'] = '80'
# 其实和第二种差不太多
config1['Test Write Third'] = {}
sub = config1['Test Write Third']
sub['Redis.host'] = '127.0.0.1'
sub['Redis.port'] = '6379'
# 这里可以添加section
config1.add_section('Test Write Fourth')
config1.set('Test Write Fourth', 'mysql.host', '127.0.0.1')

with open('example.ini', 'w') as f:
config1.write(f)

最后写入结果example.ini

1
2
3
4
5
6
7
8
9
10
11
12
13
[Test Write First]
name = cco
age = 20

[Test Write Second]
wight = 80

[Test Write Third]
redis.host = 127.0.0.1
redis.port = 6379

[Test Write Fourth]
mysql.host = 127.0.0.1

常用的也就这些,有需要了解其他的特性,可以参阅官方文档

Cco.Xyz wechat
坚持原创技术分享,您的支持将鼓励我继续创作!
0%