python中使用configparser库,实现配置文件的读取

python中使用configparser库,实现配置文件的读取,第1张

概述背景: 在写接口自动化框架,配置数据库连接时,测试环境和UAT环境的连接信息不一致,这时可以将连接信息写到conf或者cfg配置文件中 python环境请自行准备。 python代码直接封装成类,方便

背景:

在写接口自动化框架,配置数据库连接时,测试环境和UAT环境的连接信息不一致,这时可以将连接信息写到conf或者cfg配置文件中

python环境请自行准备。

python代码直接封装成类,方便其他模块的引入。

 1 from configparser import ConfigParser 2  3 class DoConfig: 4     def __init__(self,filepath,enCoding='utf-8'): 5         self.cf = ConfigParser() 6         self.cf.read(filepath,enCoding) 7  8     #获取所有的section 9     def get_sections(self):10         return self.cf.sections()11 12     #获取某一section下的所有option13     def get_option(self,section):14         return self.cf.options(section)15 16     #获取section、option下的某一项值-str值17     def get_strValue(self,section,option):18         return self.cf.get(section,option)19 20     # 获取section、option下的某一项值-int值21     def get_intValue(self,option):22         return self.cf.getint(section,option)23 24     # 获取section、option下的某一项值-float值25     def get_floatValue(self,option):26         return self.cf.getfloat(section,option)27 28     # 获取section、option下的某一项值-bool值29     def get_boolValue(self,option):30         return self.cf.getboolean(section,option)31 32     def setdata(self,option,value):33         return self.cf.set(section,value)34 35 if __name__ == '__main__':36     cf = DoConfig('demo.conf')37     res = cf.get_sections()38     print(res)39     res = cf.get_option('db')40     print(res)41     res = cf.get_strValue('db','db_name')42     print(res)43     res = cf.get_intValue('db','db_port')44     print(res)45     res = cf.get_floatValue('user_info','salary')46     print(res)47     res = cf.get_boolValue('db','is')48     print(res)49 50     cf.setdata('db','db_port','3306')51     res = cf.get_strValue('db','db_port')52     print(res)

 

总结

以上是内存溢出为你收集整理的python中使用configparser库,实现配置文件的读取全部内容,希望文章能够帮你解决python中使用configparser库,实现配置文件的读取所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1198568.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存