|
is not a separator. It is the header of a block scalar, meaning the value of examples
is a scalar with the content "- hey\n- hello\n- hi\n- hello there\n"
. To append another sequence item with the same semantic structure, you'll need to do
with open('nlu.yml', 'r') as yamlfile:
cur_yaml = yaml.safe_load(yamlfile)
cur_yaml['nlu'].append({ 'intent': 'name', 'examples': "- first\n- second\n"})
Complete working example:
import yaml, sys
input = """
nlu:
- intent: greet
examples: |
- hey
- hello
- hi
- hello there
"""
cur_yaml = yaml.safe_load(input)
cur_yaml['nlu'].append({ 'intent': 'name', 'examples': "- first\n- second"})
yaml.safe_dump(cur_yaml, sys.stdout)
This outputs
nlu:
- examples: '- hey
- hello
- hi
- hello there
'
intent: greet
- examples: '- first
- second
'
intent: name
Now while this output has the correct YAML semantic, you may dislike the way it's formatted. For an in-depth explanation of why this is happening, see this question.
The takeaway from the answer there for you is that to preserve style, you need to modify the content of your YAML file on a lower level so that Python doesn't forget the original style. I have shown how to do that in this answer. Using the functions defined there, you can reach your desired output like this:
append_to_yaml("input.yaml", "output.yaml", [
AppendableEvents(["nlu"],
[MappingStartEvent(None, None, True), key("intent"), key("name"),
key("examples"), literal_value("- hello there\n- general Kenobi\n"),
MappingEndEvent()])])
This will transform your YAML input into
nlu:
- intent: greet
examples: |
- hey
- hello
- hi
- hello there
- intent: name
examples: |
- hello there
- general Kenobi