python将字典对象保存转化为yaml格式文件
yaml.dump() 函数
yaml.dump() 函数是将 Python 对象转换为 YAML 格式的字符串的函数。下面是该函数的参数作用详细介绍:
1. data :需要转换为 YAML 格式的 Python 对象。
2. stream :指定输出的文件对象。默认情况下,输出到标准输出。
3. Dumper :指定使用的 Dumper 类型。默认情况下,使用 SafeDumper 。
4. allow_unicode :如果为 True ,则允许使用 Unicode 字符。默认为 False 。
5. default_flow_style :如果为 True ,则使用流样式输出。如果为 False ,则使用块样式输出。默认为 True 。
6. explicit_start :如果为 True ,则在输出中包含显式的文档开始标记。默认为 False 。
7. explicit_end :如果为 True ,则在输出中包含显式的文档结束标记。默认为 False 。
8. version :指定输出的 YAML 版本。默认为 None 。
9. tags :指定要使用的标签。默认为 None 。
10. sort_keys :如果为 True ,则按键排序输出。默认为 False 。
11. default_style :参数用于指定输出的 YAML 字符串的默认样式。
下面是 default_style 可以接受的值以及它们的含义:
- ‘’ 或 None :使用流样式输出。这是默认值。
- ‘|’ :使用竖线样式输出,保留换行符。
- ‘>’ :使用折叠样式输出,将换行符替换为空格。
- ‘+’ :使用 JSON 样式输出。
- ‘&’ :使用别名样式输出。
- ‘*’ :使用别名样式输出。
import os
import yaml
def save_dict_to_yaml(dict_value: dict, save_path: str):
"""
dict保存为yaml
"""
save_path = os.path.join(os.getcwd(), save_path) # Define save path with specific file path and name
try:
directory = os.path.dirname(save_path)
if not os.path.exists(directory):
os.makedirs(directory)
with open(save_path, 'w+') as file:
# Add input validation to ensure only trusted data is being passed to yaml.dump
if isinstance(dict_value, dict):
yam_str = yaml.dump(dict_value, default_style='+', default_flow_style=False, allow_unicode=True, explicit_start=True, explicit_end=True, sort_keys=True)
print(yam_str)
file.write(yam_str)
else:
print("Error: dict_value must be a dictionary")
except Exception as e:
print(f"Error: {e}") # Add error handling to gracefully handle any errors that occur and provide useful feedback to the user
def read_yaml_to_dict(yaml_path: str, ):
with open(yaml_path) as file:
dict_value = yaml.load(file.read(), Loader=yaml.FullLoader)
return dict_value