我正在处理由计算应用程序处理的YAML文件。此应用程序只支持~进行None分配,但ruamel.yaml同时使用''和null关键字。
例如:
from ruamel.yaml import YAML
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
yaml = YAML()
info = yaml.load(yaml_example)
with open('textfile.yaml', 'w') as file:
yaml.dump(info, file)这会让
info:
value1:
value2: [5, null, 12]但是,我需要输出如下所示:
info:
value1: ~
value2: [5, ~, 12]如何使用~获得输出
我已经看过以下问题,但我未能成功地将其应用于ruamel.yaml。
发布于 2021-08-05 16:32:30
您必须为空标记更改代理:
import sys
import ruamel.yaml
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
def _represent_none(self, data):
if len(self.represented_objects) == 0 and not self.serializer.use_explicit_start:
return self.represent_scalar('tag:yaml.org,2002:null', 'null')
return self.represent_scalar('tag:yaml.org,2002:null', "~")
ruamel.yaml.representer.RoundTripRepresenter.add_representer(type(None), _represent_none)
yaml = ruamel.yaml.YAML()
info = yaml.load(yaml_example)
yaml.dump(info, sys.stdout)这意味着:
info:
value1: ~
value2: [5, ~, 12]https://stackoverflow.com/questions/68670107
复制相似问题