Formatting YAML data on a file

When we write YAML files, we generally do something like this:

from pathlib import Path
import yaml
with Path("some_destination.yaml").open("w", encoding="UTF-8") as target: yaml.dump(some_collection, target)

We open the file with the required encoding. We provide the file object to the yaml.dump() method; the output is written there. When we read YAML files, we will use a similar technique:

from pathlib import Path
import yaml
with Path("some_source.yaml").open(encoding="UTF-8") as source:
objects= yaml.load(source)

The idea is to segregate the YAML representation as text from any conversion to bytes on the resulting file. We have several formatting options to create a prettier YAML representation of our data. Some of the options are shown in the following table:

explicit_start

If true, writes a --- marker before each object.

explicit_end

If true, writes a ... marker after each object. We might use this or explicit_start if we're dumping a sequence of YAML documents into a single file and need to know when one ends and the next begins.

version

Given a pair of integers (x, y), writes a %YAML x.y directive at the beginning. This should be version=(1,2).

tags

Given a mapping, it emits a YAML %TAG directive with different tag abbreviations.

canonical

If true, includes a tag on every piece of data. If false, a number of tags are assumed.

indent

If set to a number, changes the indentation used for blocks.

width

If set to a number, changes the width at which long items are wrapped to multiple, indented lines.

allow_unicode

If set to true, permits full Unicode without escapes. Otherwise, characters outside the ASCII subset will have escapes applied.

line_break

Uses a different line-ending character; the default is a newline.

 

Of these options, explicit_end and allow_unicode are perhaps the most useful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset