RODY/app/utils/YamlTool.py
552068321@qq.com 6f7de660aa first commit
2022-11-04 17:37:08 +08:00

41 lines
1.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import yaml
import os
# 单个文档
def get_yaml_data(yaml_file):
# 打开yaml文件
file = open(yaml_file, 'r', encoding='utf-8')
file_data = file.read()
file.close()
# 将字符串转化为字典或列表
data = yaml.safe_load(file_data) # safe_loadsafe_load,unsafe_load
return data
# yaml文件中含多个文档时分别获取文档中数据
def get_yaml_load_all(yaml_file):
# 打开文件
file = open(yaml_file, 'r', encoding='utf-8')
file_data = file.read()
file.close()
all_data = yaml.load_all(file_data, Loader=yaml.FullLoader)
for data in all_data:
print('data-----', data)
# 生成yaml文档
def generate_yaml_doc(yaml_file):
py_ob = {"school": "zhang", "students": ['a', 'b']}
file = open(yaml_file, 'w', encoding='utf-8')
yaml.dump(py_ob, file)
file.close()
if __name__ == '__main__':
current_path = os.path.abspath("../../")
yaml_path = os.path.join(current_path, "config.yaml")
print('--------------------', yaml_path)
get_yaml_data(yaml_path)