简体   繁体   中英

Preserving lists in ruamel.yaml

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:

  1. it puts the list in one line
  2. 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.

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, you could use such a mechanism. However since superfluous 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM