【发布时间】:2021-09-26 09:29:04
【问题描述】:
我正在尝试使用ruamel.yaml Python 库从大型 YAML 文件中的嵌套字典中删除一些键/值对,同时保留周围的 cmets。这是我正在使用的代码的简化版本:
import sys
import ruamel.yaml
with open(sys.argv[1], 'r') as doc:
parsed = ruamel.yaml.round_trip_load(doc, preserve_quotes=True)
for item in parsed['items']:
if item['color'] == 'blue':
del item['color']
yaml = ruamel.yaml.YAML(typ='rt')
yaml.indent(sequence=4, offset=2)
yaml.dump(parsed, sys.stdout)
...以及我正在尝试编辑的随附文件(目的是删除“颜色:蓝色”行:
▶ cat items.yml
items:
- name: a
color: blue
texture: smooth
# This is a comment above 'c'
# More comment
- name: b
texture: wrinkled
color: yellow
使用该特定文件,代码可以执行我想要的操作:
▶ ./munge.py items.yml
items:
- name: a
texture: smooth
# This is a comment above 'c'
# More comment
- name: b
texture: wrinkled
color: yellow
但是,如果 color: blue 是第一个字典中的 last 键/值对,则第二个项目之前的注释会被吃掉:
▶ cat items.yml
items:
- name: a
texture: smooth
color: blue
# This is a comment above 'c'
# More comment
- name: b
texture: wrinkled
color: yellow
▶ ./munge.py items.yml
items:
- name: a
texture: smooth
- name: b
texture: wrinkled
color: yellow
看起来评论附加到字典的最后一个键/值对,而不是表示为第二项之前的“前导”评论。
即使删除字典中的最后一个键,是否有任何方法可以保留下一项之前的注释?
【问题讨论】:
标签: python yaml ruamel.yaml