如何使用ruamel.yaml将列表对应的修改内容转储写入到文件中
问题原因
- 你使用的搭配
RoundTripRepresenter的自动转储方案默认仅监听字典赋值操作,嵌套在列表内的字典修改、列表本身的增删操作都不会触发自动持久化逻辑,因此修改仅停留在内存变量中,不会写入文件。 - 你的示例代码存在语法错误:
network是字典类型,没有append方法,直接调用会抛出属性错误,需要确认你要追加元素的目标列表。
解决方法
方案1:手动触发保存(更稳定,推荐)
修改完成后主动调用dump方法将内存中的配置写回文件,修正后的代码如下:
from pathlib import Path from ruamel.yaml import YAML class YamlUpdate: def __init__(self): self.config_file = Path.home() / "alper.yaml" self.yaml = YAML() # 保留原文件格式、注释等特性 self.yaml.preserve_quotes = True # 读取配置文件到内存 with open(self.config_file, 'r', encoding='utf-8') as f: self.network_config = self.yaml.load(f) self.change_item() # 修改完成后主动保存到文件 self.save_config() def change_item(self): for network in self.network_config["live"]: if network["name"] == "Ethereum": # 修改字典字段 network["name"] = "alper" print(network) # 示例:给networks列表追加新的链配置 network["networks"].append({ "chainid": 5, "explorer": "https://api-goerli.etherscan.io/api" }) # 如果要给live列表追加新的网络配置,使用如下写法 # self.network_config["live"].append({ # "name": "Polygon", # "networks": [{"chainid": 137, "explorer": "https://api.polygonscan.com/api"}] # }) def save_config(self): # 将内存中的配置写回文件 with open(self.config_file, 'w', encoding='utf-8') as f: self.yaml.dump(self.network_config, f) yy = YamlUpdate() print(yy.config_file.read_text())
运行后配置文件会更新为:
live: - name: alper networks: - chainid: 1 explorer: https://api.etherscan.io/api - chainid: 5 explorer: https://api-goerli.etherscan.io/api
方案2:扩展自动转储支持列表操作
如果需要保留自动持久化能力,需要自定义继承自ruamel.yaml的CommentedSeq的列表类,重写append、pop、__setitem__等所有会修改列表内容的方法,每次方法调用后触发写文件逻辑,再将自定义列表类注册到YAML解析器中即可。
内容的提问来源于stack exchange,提问作者alper
相关产品推荐
相关产品推荐

