I am trying to remove few attributes from YAML file and I am successful in doing so but it has some extra characters in the output file and not sure how to remove those.
Here is the input YAML file:
Person:
Name: John
Children:
- Stacy
- Rick
- Josh
Wife:
Name: Mary
Id: 123
and I am expecting the YAML file as follows, after removing few attributes:
Person:
Name: John
Children:
- Rick
- Stacy
Here is the script I am using:
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)
and this is the file it generates:
Person: !!omap
- Name: John
- Children:
- Rick
- Stacy
- How can I remove
!!omaptext that is on first line? - How can I remove
-(dash) that is next toNameandChildren?
I know that having these characters in the file does not affect the functionality but I am curious as how to remove those characters that are not present in the input file.
I am using Python3 and ruamel.yaml version is 0.17.4