我正在尝试生成一个YAML文件,它不会与这里描述的Norway问题相冲突:https://hitchdev.com/strictyaml/why/implicit-typing-removed/
我在python 3.8中运行ruamel.yaml0.17.21。
下面是我正在运行的代码:
import sys
from ruamel.yaml import YAML, round_trip_dump
data = [
[1, """first value""", "first comment"],
[2, '"second value"', "second comment"],
["abc", "None", 'this is a "comment"'],
["""def1""", "None", 'this is a "comment"'],
]
yaml = YAML()
yaml.preserve_quotes = True
code = yaml.load(
"""\
en:
"""
)
for i, item in enumerate(data):
code.insert(i + 1, str(item[0]), "" + str(item[1]) + "", comment=item[2])
print("\nthis strips quotes; but preserves comments:")
yaml.dump(code, sys.stdout)
print("\nthis preserves quotes; but strips comments:")
round_trip_dump(code, sys.stdout, default_style="'")
print("\ndesired result:")
print(
"'en':\n
'1': 'first value' # first comment\n
'2': 'second value' # second comment\n
'abc': 'None' # this is a ""comment""\n
'def1': 'None' # this is a ""comment"""
)
1条答案
按热度按时间e4yzc0pl1#
感谢@Anthon和@JonSG的建设性反馈,基于此,我找到了这篇文章How to correctly output strings with ruamel.yaml
因此,我的工作解决办法是: