我试图从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
- StacyChildren
!!omap文本?-(破折号),位于Name和我知道文件中有这些字符并不影响功能,但我很好奇如何删除输入文件中不存在的字符。
我使用的Python3和ruamel.yaml版本是0.17.4
发布于 2021-06-16 07:50:54
在YAML中,映射被定义为不被排序,尽管键在YAML文档中当然有一定的顺序。因此,如果您转储显式有序的映射,就像Python的OrderedDict一样,保证排序是通过转储带有!!omap标记的单个映射序列(总是有序的)。如果要将输出读回,则在使用OrderedDict时将再次获得ruamel.yaml,因此正如您已经注意到的,没有什么问题(但是一些处理输出链的工具可能无法正确地处理这个问题)。
在较新的Python 3实现中,字典是有序的,并将在没有这种标记的情况下被转储,并且没有保证顺序所需的序列。对于Python的2.7+来说,同样的效果可以通过使用CommentedMap来实现,它充当OrderedDict (而不转储标记):
import sys
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap as OrderedDict
file_path = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_path))
yaml = ruamel.yaml.YAML()
yaml.indent(sequence=ind, offset=bsi) # set the original sequence indent and offset of the dash
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]
yaml.dump(config, sys.stdout)这意味着:
Person:
Name: John
Children:
- Rick
- Stacy请注意,自2007年以来,官方推荐的包含YAML文档的文件扩展名为.yaml。更让人困惑的是,还有一种更老的,但并不是经常遇到的YML格式,这是一个XML派生。因此,请考虑更新您的扩展和代码。
https://stackoverflow.com/questions/67994516
复制相似问题