Python使用configparser库读取配置文件

作者:奔奔-武 时间:2022-12-21 20:22:56 

这篇文章主要介绍了Python使用configparser库读取配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

背景:

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

python环境请自行准备。

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


from configparser import ConfigParser

class DoConfig:
 def __init__(self,filepath,encoding='utf-8'):
   self.cf = ConfigParser()
   self.cf.read(filepath,encoding)

#获取所有的section
 def get_sections(self):
   return self.cf.sections()

#获取某一section下的所有option
 def get_option(self,section):
   return self.cf.options(section)

#获取section、option下的某一项值-str值
 def get_strValue(self,section,option):
   return self.cf.get(section,option)

# 获取section、option下的某一项值-int值
 def get_intValue(self, section, option):
   return self.cf.getint(section, option)

# 获取section、option下的某一项值-float值
 def get_floatValue(self, section, option):
   return self.cf.getfloat(section, option)

# 获取section、option下的某一项值-bool值
 def get_boolValue(self, section, option):
   return self.cf.getboolean(section, option)

def setdata(self,section,option,value):
   return self.cf.set(section,option,value)

if __name__ == '__main__':
 cf = DoConfig('demo.conf')
 res = cf.get_sections()
 print(res)
 res = cf.get_option('db')
 print(res)
 res = cf.get_strValue('db','db_name')
 print(res)
 res = cf.get_intValue('db','db_port')
 print(res)
 res = cf.get_floatValue('user_info','salary')
 print(res)
 res = cf.get_boolValue('db','is')
 print(res)

cf.setdata('db','db_port','3306')
 res = cf.get_strValue('db', 'db_port')
 print(res)

来源:https://www.cnblogs.com/benben-wu/p/10558792.html

标签:Python,configparser,读取,配置,文件
0
投稿

猜你喜欢

  • 如何解决从文本文件中调出记录出现丢失换行的问题?

    2009-12-03 20:25:00
  • jupyter notebook 恢复误删单元格或者历史代码的实现

    2022-03-03 16:13:45
  • Keras目标检测mtcnn facenet搭建人脸识别平台

    2023-09-28 07:02:01
  • python实现微信跳一跳辅助工具步骤详解

    2023-08-02 11:11:40
  • Python SSL证书验证问题解决方案

    2022-11-06 13:54:35
  • java常用正则表达式

    2023-04-24 11:38:36
  • Python数据类型转换汇总

    2023-05-13 16:33:00
  • mysql游标的原理与用法实例分析

    2024-01-15 16:33:36
  • Python内置的字符串处理函数详细整理(覆盖日常所用)

    2023-10-10 22:46:36
  • 使用Go HTTP客户端打造高性能服务

    2024-05-05 09:28:29
  • python轻松实现代码编码格式转换

    2023-11-27 05:47:36
  • Python安装第三方库攻略(pip和Anaconda)

    2023-02-01 22:16:41
  • Flask URL传参与视图映射的实现方法

    2021-05-10 12:31:06
  • python 包之 Pillow 图像处理教程分享

    2022-02-22 01:22:48
  • python画环形图的方法

    2023-02-12 09:54:24
  • Win10系统提示“Python 0x80070643安装时发生严重错误”怎么办?

    2023-06-13 06:50:25
  • thinkphp6如何使用中间件记录行为日志

    2023-06-13 14:43:44
  • python操作日期和时间的方法

    2021-08-29 18:32:59
  • 在PyCharm导航区中打开多个Project的关闭方法

    2022-08-11 01:39:11
  • Go语言error的设计理念及背景演化详解

    2024-02-09 22:09:19
  • asp之家 网络编程 m.aspxhome.com