Python YAML saves a new line without adding an extra line to a line

I have a similar problem with this question , that I need to insert new lines in the YAML display value string and prefer not to insert \n myself. The answer involves using:

 Data: | Some data, here and a special character like ':' Another line of data on a separate line 

instead

 Data: "Some data, here and a special character like ':'\n Another line of data on a separate line" 

which also adds a new line to the end , which is unacceptable.

I tried using Data: > , but showed that it gives completely different results. I read the final new line after reading in the yaml file, and of course this works, but it is not elegant. Any better way to keep newline characters without adding extra at the end ?

I am using python 2.7 fwiw

+6
source share
1 answer

If you use | , this makes the scanner literal-style scalar. But the default behavior | , is a trim, and this does not give you the line you need (since this leaves the final new line).

You can "change" behavior | by adding block lock indicators

Gas

Stripping is indicated by the "-" indicator. In this case, the final line break and any final empty lines are excluded from the contents of the scalars.

Clip

Trimming is the default behavior used if the explicit chomping indicator is not specified. In this case, the final line break character is stored in the contents of the scalars. However, any trailing blank lines are excluded from the contents of the scalars.

Save

Saving is indicated by the โ€œ+โ€ indicator. In this case, the final line break and any trailing blank lines are considered part of the contents of the scalars. These additional lines are not foldable.

By adding the stripchomping operator ' - ' to ' | ', you can prevent / remove the final newline: ยน

 import ruamel.yaml as yaml yaml_str = """\ Data: |- Some data, here and a special character like ':' Another line of data on a separate line """ data = yaml.load(yaml_str) print(data) 

gives:

{'Data': "Some data here and a special character like :: \\ Another line of data on a separate line"}


ยน This was done using ruamel.yaml , of which I am the author. You should get the same result with PyYAML (from which ruamel.yaml is a superset storing comments and literal scalar blocks in the opposite direction).

+4
source

Source: https://habr.com/ru/post/989665/


All Articles