【问题标题】:Value change with ruamel yaml won't work and ignores indenting使用 ruamel yaml 更改值将不起作用并忽略缩进
【发布时间】:2017-08-03 18:25:30
【问题描述】:

我在以正确格式将数据转储回 YAML 时遇到问题。调查了其他类似的问题,但没有找到解决这个问题的方法。 Python 中的当前代码:

template = yaml.load(open(templateFile), Loader=yaml.RoundTripLoader)

template["key"] = new_value

yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)

输入:

parameters:
  key: value

输出:

parameters:
  key: value
key: new_value

预期输出:

parameters:
  key: new_value

应如何修改代码,以更改旧的“键”值,或输入具有正确缩进的新值?

【问题讨论】:

  • “调查其他类似问题”包括链接和解释为什么不请。

标签: python-2.7 indentation pyyaml ruamel.yaml


【解决方案1】:

您必须将new_value 分配给正确的映射/字典:

import sys
from ruamel import yaml

template_file = 'input.yaml'
new_value = 'new_value'

template = yaml.load(open(template_file), Loader=yaml.RoundTripLoader)
template['parameters']['key'] = new_value
yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)

缩进“低于”key 的新值需要:

template['parameters']['newkey'] = 'added_value'

请注意,对于template_fileRoundTripLoader/RoundTripDumper 是类的名称)等 Python 变量,习惯上使用 snake_case

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2019-09-08
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多