Home > Enterprise >  How to add a newline between sequences with Pyyaml?
How to add a newline between sequences with Pyyaml?

Time:10-12

I've searched and I haven't found very much information on this. I'm writing a Python script to take a list of dictionaries and dump it to a yaml file. For example, I have code like the following:

import yaml

dict_1 = {'name'  : 'name1',
          'value' : 12,
          'list'  : [1, 2, 3],
          'type'  : 'doc'
}

dict_2 = {'name'  : 'name2',
          'value' : 100,
          'list'  : [1, 2, 3],
          'type'  : 'cpp'
}

file_info = [dict_1, dict_2]

with open('test_file.yaml', 'w ') as f:
    yaml.dump(file_info, f)

The output that I get is:

- list:
  - 1
  - 2
  - 3
  name: name1
  type: doc
  value: 12
- list:
  - 1
  - 2
  - 3
  name: name2
  type: cpp
  value: 100

When what I really want is something like this:

- list:
  - 1
  - 2
  - 3
  name: name1
  type: doc
  value: 12
                  ## Notice the line break here
- list:
  - 1
  - 2
  - 3
  name: name2
  type: cpp
  value: 100

I've tried putting \n and the end of the dictionaries, using file_info.append('\n') between the dictionaries, using None as a final key in the dictionary, but nothing has worked so far. Any help is greatly appreciated!

I'm using Pyyaml 5.4.1 with Python 3.9.

CodePudding user response:

You can dump each object one at a time following each with a new line.

with open('test_file.yaml', 'w ') as f:
    for yaml_obj in file_info:
        f.write(yaml.dump([yaml_obj]))
        f.write("\n")
  • Related