Search code examples
pythonyamlruamel.yaml

How to write recipe files to a yml doc from Python using ruamel.yaml


I am trying to write a script that will take arguments and write it to a yml file so i can run a snowfakery query. Snowfakery requires the first few lines be recipe lines and the rest of the lines do not need -

- snowfakery_version: version
- object: obj
  fields:
     name: John Doe

I have tried

snowfakeryTest = {
    "- snowfakery_version": 3,
    "- object": "obj",
    "fields":{
        "name": "John doe"
    }
}

with open("simple.yml", 'w') as outfile:
    yaml_dump(snowfakeryTest, outfile,)

but the yml that is generate always looks like the image provided enter image description here


Solution

  • YAML is a representation of a data structure. You need to create the appropriate data structure in memory and pass that to yaml_dump.

    Your example document shows an outer data structure that's a list; it contains two dictionaries (and the second dictionary contains a nested dictionary). In Python, that would be:

    snowfakeryTest = [
      {"snowfakery_version": "version"},
      {
        "object": "obj",
        "fields": {
          "name": "John Doe",
        },
      }
    ]
    

    If we dump that (I'm using PyYAML instead of ruamel.yaml), we get:

    - snowfakery_version: version
    - fields:
        name: John Doe
      object: obj