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()
浙公网安备 33010602011771号