安装库
pip install pyyaml
读取yaml/yam格式的文件
def get_yaml(filepath) -> list:
"""
:param filepath: 文件路径
:return: 传入数据的列表
"""
data = open(filepath, 'r', encoding='utf-8')
res = yaml.load(data, Loader=yaml.FullLoader)
data.close()
return res
写入数据,通过type参数来控制覆盖或追加
def write_yaml(filepath, data, type) -> None:
"""
:param filepath: 文件路径
:param list: 参数列表
:param type: W:覆盖编辑 A:追加编辑
"""
cur_path = os.path.dirname(os.path.realpath(__file__))
yaml_path = os.path.join(cur_path, filepath)
with open(yaml_path, type, encoding="utf-8") as f:
yaml.dump(data, stream=f, allow_unicode=True, )
清除文件内容
def clear_yaml_data(filepath) -> None:
"""
:param filepath: 文件路径
"""
fo = open(filepath, 'w', encoding='utf-8')
fo.truncate()
标签:pyyaml,filepath,Python,type,param,yaml,path,data
From: https://www.cnblogs.com/ppxs/p/16710228.html