python-通过configparser模块读取后缀为 .ini 的配置文件信息

前言
一般为了方便会将路径,连接信息等写到配置文件(通常会将这些信息写到yaml,ini....配置文件)中,configparser模块读取后缀为 .ini 的配置文件信息

配置文件格式


#存在 config.ini 配置文件,内容如下:
[DEFAULT]
excel_path = ../test_cases/case_data.xlsx
log_path = ../logs/test.log
log_level = 1

[email]
user_name = 32@qq.com
password = 123456

读取配置文件的基本语法


import configparser

#创建配置文件对象
conf = configparser.ConfigParser()
#读取配置文件
conf.read('config.ini', encoding="utf-8")
#列表方式返回配置文件所有的section
print( conf.sections() )    #结果:['default', 'email']
#列表方式返回配置文件email 这个section下的所有键名称
print( conf.options('email') )    #结果:['user_name', 'password']
#以[(),()]格式返回 email 这个section下的所有键值对
print( conf.items('email') )    #结果:[('user_name', '32@qq.com'), ('password', '123456')]
#使用get方法获取配置文件具体的值,get方法:参数1-->section(节) 参数2-->key(键名)
value = conf.get('default', 'excel_path')
print(value)

项目实践

posted @ 2020-08-04 17:48  我是海底的咸鱼  阅读(175)  评论(0编辑  收藏  举报