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,读取,配置,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈Python3中datetime不同时区转换介绍与踩坑
2021-05-16 15:29:46
Python正则表达式中group与groups的用法详解
2022-02-13 16:16:27
![](https://img.aspxhome.com/file/2023/7/81597_0s.png)
pandas修改DataFrame列名的方法
2021-07-18 16:41:24
Python编程给numpy矩阵添加一列方法示例
2023-08-29 07:22:30
python编程羊车门问题代码示例
2023-04-10 18:39:19
python merge、concat合并数据集的实例讲解
2023-01-23 16:30:38
Python数学建模学习模拟退火算法多变量函数优化示例解析
2021-05-07 09:36:37
Pycharm学生免费专业版安装教程的方法步骤
2022-01-11 14:39:30
![](https://img.aspxhome.com/file/2023/6/124746_0s.png)
python3使用print打印带颜色的字符串代码实例
2022-01-20 10:30:49
Python面向对象类的继承实例详解
2023-04-19 11:06:38
使用pandas实现筛选出指定列值所对应的行
2023-05-06 18:29:53
![](https://img.aspxhome.com/file/2023/2/101032_0s.png)
用JAVASCRIPT格式化数字成货币(逗号隔开)
2008-01-30 12:34:00
python通过pil模块获得图片exif信息的方法
2021-08-26 14:31:21
Python中提取人脸特征的三种方法详解
2023-11-06 09:38:04
创建SparkSession和sparkSQL的详细过程
2023-02-13 14:40:40
![](https://img.aspxhome.com/file/2023/3/77863_0s.jpg)
python-opencv-cv2.threshold()二值化函数的使用
2022-12-31 23:00:12
![](https://img.aspxhome.com/file/2023/2/92522_0s.png)
ThinkPHP基于think-queue的队列插件实现消息推送
2023-05-25 05:59:12
使用django实现一个代码发布系统
2022-06-28 02:42:45
![](https://img.aspxhome.com/file/2023/4/65114_0s.png)
十行Python3代码实现去除pdf文件水印
2022-02-27 10:50:15
![](https://img.aspxhome.com/file/2023/0/102780_0s.jpg)
Python实现将图像转换为ASCII字符图
2022-07-15 06:05:20
![](https://img.aspxhome.com/file/2023/3/92343_0s.jpg)