Save quotes as well as add quoted data in Ruamel

I use Ruamel to save quote styles in user editable YAML files.

I have an example input like:

---
a: '1'
b: "2"
c: 3

I am reading data using:

def read_file(f):
    with open(f, 'r') as _f:
        return ruamel.yaml.round_trip_load(_f.read(), preserve_quotes=True)

Then I edit this data:

data = read_file('in.yaml')
data['foo'] = 'bar'

I am writing back to disk using:

def write_file(f, data):
    with open(f, 'w') as _f:
        _f.write(ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper, width=1024))

write_file('out.yaml', data)

And the output file:

a: '1'
b: "2"
c: 3
foo: bar

Is there a way to force a strict quotation of the string "bar" without using this quote style throughout the rest of the file?

(Also, can I stop him from removing three strokes ---?)

+6
source share
2 answers

( ) , ruamel.yamlยน - - - SingleQuotedScalarString, DoubleQuotedScalarString PreservedScalarString. scalarstring.py. " ", , - , .

- ( ), :

import sys
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString

yaml_str = """\
---
a: '1'
b: "2"
c: 3
"""

yaml = YAML()
yaml.preserve_quotes = True
yaml.explicit_start = True
data = yaml.load(yaml_str)
data['foo'] = SingleQuotedScalarString('bar')
data.yaml_add_eol_comment('# <- single quotes added', 'foo', column=20)
yaml.dump(data, sys.stdout)

:

---
a: '1'
b: "2"
c: 3
foo: 'bar'          # <- single quotes added

yaml.explicit_start = True () . , "" , .

, preserve_quotes, , 1 2 () , , , .


ยน .

+8

Ruamel 0.15, preserve_quotes :

from ruamel.yaml import YAML
from pathlib import Path

yaml = YAML(typ='rt') # Round trip loading and dumping
yaml.preserve_quotes = True
data = yaml.load(Path("in.yaml"))
yaml.dump(data, Path("out.yaml"))
+2

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


All Articles