ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)
配置信息读取配置文件:
read(filename) # 读取配置文件,直接读取ini文件内容
sections() # 获取ini文件内所有的section,以列表形式返回['logging', 'mysql']
options(sections) # 获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password']
items(sections) # 获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
get(section, option) # 获取section中option的值,返回为string类型
演示
配置文件ini如下:
[logging] level = 20 path = server = [mysql] host=127.0.0.1 port=3306 user=root password=123456
代码如下:
import configparser
conf = configparser.ConfigParser()
file_path = "txt.ini"
print('file_path :', file_path)
conf.read(file_path)
sections = conf.sections()
print('获取配置文件所有的section', sections)
options = conf.options('mysql')
print('获取指定section下所有option', options)
items = conf.items('mysql')
print('获取指定section下所有的键值对', items)
value = conf.get('mysql', 'host')
print('获取指定的section下的option', type(value), value)
运行结果:
- file_path : txt.ini
- 获取配置文件所有的section [‘logging’, ‘mysql’]
- 获取指定section下所有option [‘host’, ‘port’, ‘user’, ‘password’]
- 获取指定section下所有的键值对 [(‘host’, ‘127.0.0.1’), (‘port’, ‘3306’), (‘user’,
‘root’), (‘password’, ‘123456’)] - 获取指定的section下的option
127.0.0.1



