1.安装:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyyaml

2.操作代码:yaml_util.py:

import os
import yaml

class YamlUtil(object):

    #读取yaml文件
    #os.getcwd(),获取当前工程根目录
    def read_yaml(self):
        with open(os.getcwd()+"extract.yml",encoding="utf-8") as f:
            value = yaml.load(stream=f,Loader=yaml.FullLoader)
            return value

    #写入yaml文件
    # allow_unicode=True ,保证写入文件,用的是定义的encoding的编码,否则文件内写入的是Unicode
    def write_yaml(self,dict_data):
        with open(os.getcwd()+"extract.yml",encoding="utf-8",mode='a') as f:
           yaml.dump(data=dict_data,stream=f,allow_unicode=True)


    #清空yaml文件
    #用函数truncate(),来清空文件内容
    #因为采用的是追加的方式写入数据,所以在重新开始之前需要清除原来的数据
    def clean_yaml(self):
        with open(os.getcwd()+"extract.yml",encoding="utf-8",mode='a') as f:
            f.truncate()

  

 

posted on 2022-04-18 17:41  大话人生  阅读(61)  评论(0)    收藏  举报