python读写配置文件

Usage

配置文件config.ini如下,其中文件名和文件后缀名可以自己定义,但是格式应与其一致,中括号中的表示section,用来对变量进行分组。

1
2
3
4
5
6
7
[params]
integerVariable = 5

[other]

floatVariable = 1.5
stringVariable = hello world
booleanVariable = false

下面的代码演示了如何读写配置文件,详见注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import configparser  

# 读取配置文件
config = configparser.ConfigParser()
config.read("config.ini")

# 读取不同类型的变量
integerVariable = config.getint("params", "integerVariable")
floatVariable = config.getfloat("other", "floatVariable")
booleanVariable = config.getboolean("other", "booleanVariable")
stringVariable = config.get("other", "stringVariable")

# 添加新的分组
config.add_section("new_section")

# 写变量
config.set("other", "m", '100')
config.write(open("config.ini", 'w'))