I have a large YAML file where I need to add 2 key-values to the end of one item.
Here is an example of the format of the original file:
repo1:
description: sample description
team: sample team
repo2:
description: sample description
team: sample team
I want the output to look like:
repo1:
description: sample description
team: sample team
archived: true
archived_date: sample date
repo2:
description: sample description
team: sample team
I'm using ruamel.yaml as roundtrip keeps the formatting and comments at the top of this large file. My code to do this is as follows, it takes an input of repo_name which is the item I want to add onto:
from ruamel.yaml import YAML
yaml = YAML()
with open("repos.yml", "r") as file:
repos = yaml.load(file)
for repo in repos.items():
if repo_name == repo[0]:
repo[1].update({"archived": bool("true"), "archived_date": datetime.today().strftime('%d-%m-%Y')})
break
else:
continue
with open("repos.yml", "w") as processed_file:
yaml.default_flow_style = False
yaml.width = float("inf")
yaml.dump(repos, processed_file)
This nearly does what I want but the output looks like this:
repo1:
description: sample description
team: sample team
archived: true
archived_date: sample date
repo2:
description: sample description
team: sample team
How can I remove the blank line before what I've included and add one after it? Printing repo[1] in the loop shows the dictionary doesn't have a blank line but I want to use roundtrip to keep the rest of the formatting.