LaVOZs

The World’s Largest Online Community for Developers

'; formatting - How to write list of string to yaml file in the format of github actions using python - LavOzs.Com

The python yaml package (version 5.1.2) is able to load the following file correctly, even though the list is not written with leading -

xx: [x1, x2]
yy: [y1, y2, y3]

The loading code is as follows

import yaml

with open('some file') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

This format is used in github actions config yaml files. For example,

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [2.7, 3.5, 3.6, 3.7, 3.8]
        os: [ubuntu-16.04, ubuntu-18.04]
        node: [6, 8, 10]

But when I write data to file using yaml.dump(data, f), it takes the - convention, i.e.,

xx:
- x1
- x2
yy:
- y1
- y2
- y3

Is there a way to force it into the github-actions-like format?

I was told about default_flow_style, but it doesn't give exactly what I want.

yaml.dump({"A":[1,2,3],"B":[4,5,6]},default_flow_style=True)

The output is '{A: [1, 2, 3], B: [4, 5, 6]}\n'

Generally, it is not possible to write out YAML exactly the way it was written when you loaded it, see this question.

You can follow the advice in the answer there: Load to node graph instead of native objects. It looks like this in PyYAML:

import yaml
import io

input = """
xx: [x1, x2]
yy: [y1, y2, y3]
"""

loader = yaml.Loader(input)
node = loader.get_single_node()

stream = io.StringIO()
dumper = yaml.Dumper(stream)
dumper.open()
dumper.serialize(node)
dumper.close()
print(stream.getvalue())

Output will be:

xx: [x1, x2]
yy: [y1, y2, y3]

This works because a node still remembers its original style (while the native data doesn't). It is still possible to alter the YAML structure, but you now need to create data as nodes instead of just manipulating the loaded Python data.

If you want to create your data in Python and dump in your preferred format, the easiest way to do that would probably be:

  • create the data
  • dump it to a YAML string
  • load that string as node graph
  • walk the node graph and alter the style attribute of the nodes to your liking
  • represent the node graph as YAML again
Related
How do I copy a file in Python?
How to format numbers as currency string?
How do I get a substring of a string in Python?
How do I concatenate two lists in Python?
How can I parse a YAML file in Python
How do I list all files of a directory?
How to read a file line-by-line into a list?
How do you append to a file in Python?
How can I print literal curly-brace characters in python string and also use .format on it?
How do I lowercase a string in Python?