python接口自动化之ConfigParser配置文件的使用详解
前言:目前我们使用的绝大多数计算机程序,无论是办公软件,浏览器,甚至游戏、视频都是通过菜单界面系统配置的,它几乎成了我们使用机器的默认方式。而在python中,也有这样的一个配置模块可以把代码可配置化。
什么是配置文件
这里的配置文件不同于我们平常所见的可视化的菜单界面,它是像代码形式的,如下示例:
这是res2:['logging', 'mysql']
这是res3:['level', 'f_level', 's_level']
这是res4:[('level', 'DEBUG'), ('f_level', 'DEBUG'), ('s_level', 'ERROR')]
这是res5:DEBUG <class 'str'>
这是res6:3306 <class 'int'>
Process finished with exit code 0
除了可以读取str、int类型以外,还支持float、boolean,这里就不再举例。
🎈 小知识:
- 键值对可用
=
也可用:
进行分隔 section
名称是区分大小写的,而option不区分- 键值对中,首尾若有空白符会被去掉
- 配置文件中也可以写入注释,注释以
#
或者;
为前缀
写入配置文件
基本的写入方法如下:
add_section(section)
:添加一个新的sectionset( section, option, value)
:对section中的option进行设置,需要调用write将内容写入配置文件
from configparser import ConfigParser # 创建一个操作配置文件的对象(文件解析对象) conf = ConfigParser() conf.add_section('test') conf.set('test', 'name', 'Amy') conf.write(open('conf.ini', "a", encoding="utf-8"))
运行后查看conf.ini文件里面的内容:
ConfigParser的封装
一次封装,一劳永逸,之后直接调用即可,封装内容按需。
from configparser import ConfigParser class MyConf: def __init__(self, filename, encoding="utf8"): self.filename = filename self.encoding = encoding self.conf = ConfigParser() self.conf.read(filename, encoding) def get_str(self, section, option): return self.conf.get(section, option) def get_int(self, section, option): return self.conf.getint(section, option) def get_float(self, section, option): return self.conf.getfloat(section, option) def get_bool(self, section, option): def write_data(self, section, option, value): self.conf.set(section, option, value) self.conf.write(open(self.filename, "a", encoding=self.encoding)) if __name__ == '__main__': print(conf.get_str("conf.ini", "test","name")) # 测试
总结
到此这篇关于python接口自动化 ConfigParser配置文件的使用的文章就介绍到这了,更多相关python接口自动化ConfigParser配置文件内容请搜索来客网以前的文章或继续浏览下面的相关文章希望大家以后多多支持来客网!