介绍
ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini
配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。
注意:在python 3 中ConfigParser
模块名已更名为configparser
函数
-
读取配置文件
- read(filename) 直接读取ini文件内容
- sections() 得到所有的section,并以列表的形式返回
- options(section) 得到该section的所有option
- items(section) 得到该section的所有键值对
- get(section,option) 得到section中option的值,返回为string类型
- getint(section,option) 得到section中option的值,返回为int类型
- getfloat(section,option)得到section中option的值,返回为float类型
- getboolean(section, option)得到section中option的值,返回为boolean类型
-
写入配置文件
- add_section(section) 添加一个新的section
- has_section(section) 判断是否有section
- set( section, option, value) 对section中的option进行设置
- remove_setion(section)删除一个section
- remove_option(section, option)删除section中的option
- write(fileobject)将内容写入配置文件。
使用
配置文件config.ini
如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
注意:也可以使用:
替换=
程序:
- 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