I have a yaml file with some value as a list on multiple lines:
my_list: [1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20]
If I load and then dump this using ruamel.yaml it does two things:
- it puts the list in one line
- it adds a space between items
my_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
is there a way to leave a list alone using ruamel.yaml?
I have tried looking for documentation on ruamel.yaml but I can't find too much about this. I know that there is LiteralScalarString which helps for strings, but I sort of need an equivalent for lists.
CodePudding user response:
As it says in the introduction to the documentation
block style and key ordering are kept, so you can diff the round-tripped source
It will not preserve breaks (or comments) inserted within flow-style sequence elements (or flow-style mapping key-values).
All such flow sequences are normalised to have a space before the scalar if preceded by a flow-sequence element indicator (,
). There is no easy fix of searching for the string ', '
and replacing it with ','
because of that.
The LiteralScalarString
doesn't do much special, execpt keeping line breaks during dumping. The FoldedScalarString
does something more complex in preserving the positions where the original string was folded while allowing you to use the string as if normally loaded. To preserve the "folds" in a flow style sequence, a list of indices is kept on the object. You could use such a mechanism to "fold" flow-style sequences.
However since newlines in block-style are kept as (empty) comments it is more likely that ruamel.yaml will at some point support intra flow-style collection comments (indexed to an element, key or value) and that would give you your newline in a different way.