operate_yaml这个模块就是打基础的模块,之后的读取接口数据,config配置项等都需要用到。因为我们这些数据都是存在yaml文件中
首先还是引入库:
import yaml
import os
from common.logger import Log
1,先创建一个类:
class OperateYaml(object):
2,初始化
def __init__(self, file_path: str):
self.log = Log('操作yaml文件').get_logger()
self.file_path = file_path
3,读取yaml文件中key值的方法
def read(self, keyword):
"""
读取Yaml文件中的某个key的值
:param keyword: 需要读取的key
:return: key对应的value值
"""
if os.path.exists(self.file_path):
if self.file_path.endswith('.yaml'):
with open(self.file_path, 'r', encoding='utf-8') as e:
yaml_info = yaml.load(e.read(), Loader=yaml.FullLoader)
value = yaml_info.get(keyword)
self.log.info('读取{}中{}字段成功'.format(self.file_path, keyword))
return value
else:
raise FileTypeError('文件类型错误,必须是.yaml文件!')
else:
self.log.error('文件不存在,请确认!')
4,写入yaml文件内容
def write(self, value: dict):
"""
向yaml文件中写入值
:param value: 需要写入的值,为字典格式。
:return:
"""
with open(self.file_path, 'a', encoding='utf-8') as f:
yaml.dump(value, f, allow_unicode=True)
self.log.info('写入{}成功'.format(value))
return self
这边涉及几个os.path的使用方法
os.path.exists(path)
如果path存在,返回True;如果path不存在,返回False
file_path.endswith(’.yaml’)
用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。
这边用来判断该文件是不是yaml文件
with open
打开本地文件的,他会在使用完毕后,自动关闭文件,无需手动书写close()
下一篇:read_config模块,读取配置文件信息