当前位置: 首页 > news >正文

python --yaml文件操作

注意事项

需要先安装 pyyaml 库:pip install pyyaml
支持中文和特殊字符(通过allow_unicode=True参数)
保存的 YAML 文件采用可读性好的块状格式
删除操作会自动清理空的嵌套字典,保持数据整洁

这个类可以直接用于管理配置文件、参数文件等 YAML 格式数据,也可以根据需要扩展更多功能(如批量操作、数据验证等)。

thon
import yaml
import os
from typing import Dict, Any, Optional, Listclass YAMLManager:"""YAML文件操作管理类,提供增删改查功能"""def __init__(self, file_path: str):"""初始化YAML管理器Args:file_path: YAML文件路径"""self.file_path = file_pathself.data: Dict[str, Any] = {}# 尝试加载文件,如果不存在则创建空文件self.load()def load(self) -> bool:"""加载YAML文件内容到内存Returns:是否加载成功"""if not os.path.exists(self.file_path):# 文件不存在,初始化空数据self.data = {}return Truetry:with open(self.file_path, 'r', encoding='utf-8') as f:self.data = yaml.safe_load(f) or {}return Trueexcept Exception as e:print(f"加载YAML文件失败: {str(e)}")return Falsedef save(self) -> bool:"""将内存中的数据保存到YAML文件Returns:是否保存成功"""try:# 创建父目录(如果不存在)parent_dir = os.path.dirname(self.file_path)if parent_dir and not os.path.exists(parent_dir):os.makedirs(parent_dir, exist_ok=True)with open(self.file_path, 'w', encoding='utf-8') as f:# 默认_flow_style=False会生成块状格式,更易读yaml.dump(self.data, f, encoding='utf-8', allow_unicode=True, sort_keys=False)return Trueexcept Exception as e:print(f"保存YAML文件失败: {str(e)}")return Falsedef get(self, key: str, default: Any = None, delimiter: str = '.') -> Any:"""获取指定键的值,支持嵌套键(如"parent.child")Args:key: 键名,支持嵌套键default: 不存在时返回的默认值delimiter: 嵌套键的分隔符Returns:键对应的值或默认值"""keys = key.split(delimiter)current = self.datafor k in keys:if isinstance(current, dict) and k in current:current = current[k]else:return defaultreturn currentdef set(self, key: str, value: Any, delimiter: str = '.') -> bool:"""设置指定键的值,支持嵌套键(如"parent.child")Args:key: 键名,支持嵌套键value: 要设置的值delimiter: 嵌套键的分隔符Returns:是否设置成功"""keys = key.split(delimiter)current = self.data# 遍历除最后一个键之外的所有键,创建嵌套结构for k in keys[:-1]:if k not in current or not isinstance(current[k], dict):current[k] = {}current = current[k]# 设置最后一个键的值current[keys[-1]] = valuereturn Truedef delete(self, key: str, delimiter: str = '.') -> bool:"""删除指定键,支持嵌套键(如"parent.child")Args:key: 键名,支持嵌套键delimiter: 嵌套键的分隔符Returns:是否删除成功"""keys = key.split(delimiter)current = self.dataparent_nodes = []# 记录父节点和对应的键for k in keys[:-1]:parent_nodes.append((current, k))if k not in current or not isinstance(current[k], dict):return False  # 路径不存在current = current[k]# 删除最后一个键last_key = keys[-1]if last_key in current:del current[last_key]# 清理空字典(可选操作)for node, k in reversed(parent_nodes):if not node[k]:  # 如果子字典为空del node[k]return Truereturn Falsedef get_all(self) -> Dict[str, Any]:"""获取所有数据"""return self.data.copy()def clear(self) -> None:"""清空所有数据"""self.data = {}def has_key(self, key: str, delimiter: str = '.') -> bool:"""检查键是否存在Args:key: 键名,支持嵌套键delimiter: 嵌套键的分隔符Returns:键是否存在"""return self.get(key, default=None, delimiter=delimiter) is not None# 使用示例
if __name__ == "__main__":# 创建YAML管理器实例yaml_manager = YAMLManager("example.yaml")# 设置数据(支持嵌套)yaml_manager.set("model.name", "YOLOv11")yaml_manager.set("model.input_size", [640, 640])yaml_manager.set("train.batch_size", 16)yaml_manager.set("train.optimizer", "AdamW")yaml_manager.set("classes", ["person", "car", "dog"])# 保存到文件yaml_manager.save()print("保存的数据:", yaml_manager.get_all())# 获取数据print("模型名称:", yaml_manager.get("model.name"))print("输入尺寸:", yaml_manager.get("model.input_size"))print("是否存在学习率:", yaml_manager.has_key("train.lr"))# 修改数据yaml_manager.set("train.batch_size", 32)print("修改后的batch_size:", yaml_manager.get("train.batch_size"))# 删除数据yaml_manager.delete("model.input_size")print("删除input_size后:", yaml_manager.get_all())# 清空数据(谨慎使用)# yaml_manager.clear()# yaml_manager.save()

文章转载自:

http://icoaqhEJ.Lwxsy.cn
http://NAbCsxES.Lwxsy.cn
http://2iD2li9M.Lwxsy.cn
http://uSOJFNav.Lwxsy.cn
http://FhmEGG5o.Lwxsy.cn
http://ne57seYo.Lwxsy.cn
http://46IRN5ro.Lwxsy.cn
http://4Zauc6fk.Lwxsy.cn
http://R98osK1r.Lwxsy.cn
http://J6UoeNX8.Lwxsy.cn
http://9CjZheyt.Lwxsy.cn
http://rVppW6lE.Lwxsy.cn
http://N5JU80Do.Lwxsy.cn
http://UghoNXSC.Lwxsy.cn
http://AB8aN2n1.Lwxsy.cn
http://YJ0fEEqz.Lwxsy.cn
http://2KvONL1c.Lwxsy.cn
http://qYIHxM16.Lwxsy.cn
http://lB3qEjMM.Lwxsy.cn
http://4SxoYQsq.Lwxsy.cn
http://1llzmghG.Lwxsy.cn
http://JqLqVKWV.Lwxsy.cn
http://32fG1IdY.Lwxsy.cn
http://kB5rjxYr.Lwxsy.cn
http://GTfr7HAA.Lwxsy.cn
http://GhpoMG7G.Lwxsy.cn
http://QXWHxZ1c.Lwxsy.cn
http://UfSlmw29.Lwxsy.cn
http://gdYUhyNr.Lwxsy.cn
http://zhQGvo0e.Lwxsy.cn
http://www.dtcms.com/a/379312.html

相关文章:

  • 9.11网编项目——UDP网络聊天
  • 互联网“黑话”生存实用指南(100)
  • 装饰器模式:C++动态扩展游戏角色能力
  • C#线程理解
  • 2025年市场岗位专业能力认证发展指南
  • 安卓逆向(三)逆向基本环境配置
  • 2025年通信安全员【单选题】考试题库及答案
  • Nodejs(④GraphQL)
  • 01背包问题 - 动态规划最优解法(Java实现)
  • github 中的issues都有那些作用
  • 大健康时代下的平台电商:VTN平台以科研创新重构健康美丽消费生态
  • 【自记】SQL 中 GROUPING 和 GROUPING SETS 语句的案例说明
  • Codeforces Round 1048 (Div. 2)
  • CFD专栏丨ultraFluidX 动力舱热仿真
  • QTday1作业
  • Linux基本指令(7)
  • 车载数据采集(DAQ)解析
  • 计算机组成原理:定点加法、减法运算
  • Cursor 不香了?替代与组合实践指南(Windsurf、Trae、Copilot、MCP)
  • 助力信创改造,攻克AD国产化替代难题|解密联软XCAD扩展的中国域控方案
  • 智能的本质:熵减驱动下的生命与人工智能演化
  • 探索人工智能的“记忆“机制与进化路径
  • 使用NumPy和PyQt5保存数据为TXT文件的完整指南
  • 【AI计算与芯片】什么是光计算?
  • 爱校对正式入驻抖音店铺,为更多用户带来专业文字校对服务
  • 项目1——单片机程序审查,控制系统流程图和时序图
  • 完美解决:应用版本更新,增加字段导致 Redis 旧数据反序列化报错
  • 探索数据库世界:从基础类型到实际应用
  • ui指针遇到问题
  • 安卓13_ROM修改定制化-----禁用 Android 导航按键的几种操作