I am trying to add data to foo.yaml from a string like this:
foo.yaml
# other stuff in the file
packages: # doesn't have to exist
- 1
- 2
- 3
# other stuff in the file
the string
packages:
- 4
- 5
The 2 files aren't always the same formatting. I can't just append the other stuff because the packages: group may already exist and if it does it doesn't have to be at the end of the file.
I have tried just appending to the file but I realized it wouldn't work because packages: might already exist. Also, while I was attempting to append like that the newlines in the string got written to the file as the \n symbol instead of as an actual newline.
You should not be using PyYAML for this. It only support the YAML 1.1 specification, which was outdated in 2009. PyYAML will also happely delete any comments from your YAML files.
Load both files using
ruamel.yamland update the first file using setdefault and extend to cope withpackagespotentially not being available in the first file:which gives:
The second
# other stuf in the filecomment gets attached to the last element of the sequence. Extending the list loaded from that sequence would not move the comment, the optonal code there is to move this explicitly to the end of the new sequence.Disclaimer: I am the author of
ruamel.yaml