【发布时间】:2021-08-31 19:00:39
【问题描述】:
我正在尝试从 YAML 文件中删除一些属性并且我成功地这样做了,但是它在输出文件中有一些额外的字符并且不知道如何删除这些。
这里是输入 YAML 文件:
Person:
Name: John
Children:
- Stacy
- Rick
- Josh
Wife:
Name: Mary
Id: 123
在删除一些属性后,我期望 YAML 文件如下所示:
Person:
Name: John
Children:
- Rick
- Stacy
这是我正在使用的脚本:
import re
import time
from collections import OrderedDict
from ruamel.yaml import ruamel
file_path = '/path/to/yml/file'
# Read yaml file
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_path))
allowed_attributes = ['Name', 'Children']
allowed_children = ['Rick', 'Stacy']
root_node_name = 'Person'
config[root_node_name] = OrderedDict((attribute_name, config[root_node_name][attribute_name]) for attribute_name in allowed_attributes)
config[root_node_name]['Children'] = [child_name for child_name in allowed_children]
new_file_path = f"{re.sub('.yml','',file_path)}_{time.strftime('%Y%m%d-%H%M%S')}.yml"
with open(new_file_path, "w") as fp:
ruamel.yaml.YAML().dump(config, fp)
这是它生成的文件:
Person: !!omap
- Name: John
- Children:
- Rick
- Stacy
- 如何删除第一行的
!!omap文本? - 如何删除
Name和Children旁边的-(破折号)?
我知道文件中包含这些字符不会影响功能,但我很好奇如何删除输入文件中不存在的那些字符。
我使用的是 Python3,ruamel.yaml 版本是 0.17.4
【问题讨论】:
-
我来自荷兰,我读到你的名字是 J.A.范 Oob %-)
标签: python python-3.x yaml ruamel.yaml