(资料图片仅供参考)
1.configparser介绍
configparser是python自带的配置参数解析器。可以用于解析.config文件中的配置参数。ini文件中由sections(节点)-key-value组成
2.安装:
pip install configparse
3.获取所有的section
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#获取所有的sectionsections = cf.sections()print(sections)#输出:["CASE", "USER"]
4.获取指定section下的option
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#获取指定section下所有的optionoptions = cf.options("CASE")print(options)#输出:["caseid", "casetitle", "casemethod", "caseexpect"]
5.获取指定section的K-V
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#获取指定section下的option和value,每一个option作为一个元祖[(),(),()]alls = cf.items("CASE")print(alls)#输出:[("caseid", "[1,2,3]"), ("casetitle", "["正确登陆","密码错误"]"), ("casemethod", "["get","post","put"]"), ("caseexpect", "0000")]
6.获取指定value(1)
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#获取指定section下指定option的valuecaseid = cf.get("CASE","caseid")print(caseid)
7.获取指定value(2)
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#获取指定section下指定option的valuecaseid = cf["CASE"]["caseid"]print(caseid)#输出:[1,2,3]
8.value数据类型
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#value数据类型user = cf["USER"]["user"]print(type(user))#输出:
9.value数据类型还原eval()
import configparsercf = configparser.ConfigParser()cf.read("case.config",encoding="utf8")#读取config,有中文注意编码#value数据类型还原user = cf["USER"]["user"]print(type(user))#输出:user = eval(user)print(type(user))#输出:
10.封装
import configparserclass GetConfig(): def get_config_data(self,file,section,option): cf = configparser.ConfigParser() cf.read(file, encoding="utf8") # 读取config,有中文注意编码 # 返回value return cf[section][option]if __name__ == "__main__": values = GetConfig().get_config_data("case.config","USER","user") print(values) #输出:[{"username":"张三","password":"123456"},{"username":"李四"}]