Python configparser模块

configparser模块在python中用来读取配置文件,可以包含多个节(section),每个节可以有多个参数(健=值),使用的配置文件的好处就是不用在程序上写死。可以是程序更加的灵活。python3中,ConfigParser模块名已经更改为configparser

 

import configparser

conf = configparser.ConfigParser()

read = conf.read("mysql", encoding="utf8") # 读取配置文件,直接读取文件内容

sections = conf.sections() # 获取文件内所有的section,以列表的形式返回
print('获取配置文件所有的section', sections)

options = conf.options('logging') # 获取指定sections下的所有的options,以列表形式返回
print('获取指定section下所有option', options)

items = conf.items('mysql') # 获取指定section下所有的健值对
print('获取指定section下所有的键值对', items)

value = conf.get('mysql', 'host') # 获取section中option的值,返回为string类型
print('获取指定的section下的option', value)

返回结果如下所示:

获取配置文件所有的section ['logging', 'mysql']
获取指定section下所有option ['level', 'path', 'server']
获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', 'mysql')]
获取指定的section下的option 127.0.0.1

 

配置文件mysql内容如下:

[logging]
level = 20
path =
server =

[mysql]
host = 127.0.0.1
port = 3306
user = root
password = mysql

配置文件中,可以使用 : 替换 =

posted @ 2019-04-25 11:42  奔跑的虎皮猫  阅读(120)  评论(0编辑  收藏  举报