源码: https://github.com/yaml/pyyaml
# pip命令行安装
pip install PyYAML
# 下载源码的安装
python setup.py install
import yaml
def read_yaml(yml_file, mode='r', encoding='utf-8'):
""" yaml中内容读取并转化为Python对象
:param yml_file:
:param mode:
:param encoding:
:return:
"""
# safe_load_all() 打开多个文档
with open(yml_file, mode=mode, encoding=encoding) as y_file:
# .load 是非推荐的 不安全的编码方式
# content = yaml.load(y_file.read(), yaml.FullLoader)
# .safe_load 安全编码方式
# If you don't trust the input stream, you should use:
return yaml.safe_load(y_file)
def write_yaml(yaml_file, data, mode='w', encoding='utf-8', is_flush=True):
""" Python对象转换为 yaml
:param yaml_file:
:param data:
:param mode:
:param encoding:
:param is_flush:
:return:
"""
with open(yaml_file, mode=mode, encoding=encoding) as y_file:
# yaml.dump(data, stream=y_file)
# allow_unicode 解决写入乱码的问题
yaml.safe_dump(data, stream=y_file, allow_unicode=True)
if is_flush:
y_file.flush()