RODY/app/utils/YamlTool.py

41 lines
1.0 KiB
Python
Raw Normal View History

2022-11-04 17:37:08 +08:00
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)