The Python Oracle

How can I write data in YAML format in a file?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 How Can I Write Data In Yaml Format In A File?
00:18 Accepted Answer Score 292
00:40 Answer 2 Score 102
01:01 Answer 3 Score 2
01:32 Answer 4 Score 0
02:37 Thank you

--

Full question
https://stackoverflow.com/questions/1247...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #formatting #yaml #pyyaml

#avk47



ACCEPTED ANSWER

Score 292


import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}



ANSWER 2

Score 102


Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e



ANSWER 3

Score 2


As of 2024, I had to use sort_keys=False to maintain the specific order in the dictionary, i.e.:

import yaml

data = {
    "mode" : 'separate-outputs',
    "parent" : 'd93fca33ec026010b521b3587beb5897dff43189a8e1b4da078846c40d680dcei0',
    "postage" : 690,
    "inscriptions" : [
        {"file": "mango.avif", "metadata": {"title": "test"}},
        {"file": "mango2.avif", "metadata": {"title": "test"}},
    ]
}

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False, sort_keys=False)

data.yml

mode: separate-outputs
parent: d93fca55ec026010b521b3587beb5897dff43189a8e1b4da078846c40d680dcei0
postage: 690
inscriptions:
- file: mango.avif
  metadata:
    title: test
- file: mango2.avif
  metadata:
    title: test



ANSWER 4

Score 0


At the time this question was asked in 2012, the default flow style was None but since PyYaml 5.1, it's been False, so for recent versions of PyYaml (e.g. PyYaml 6.0.1), the nested objects are written in block style by default, i.e. the following code:

import yaml
d = {'A': 'a', 'B': {'C': 'c', 'D': 'd', 'E': 'e'}}

with open('data.yaml', 'w') as f:
    yaml.dump(d, f)

would produce a file that looks like

A: a
B:
  C: c
  D: d
  E: e

Also, if you don't pass a file handle, dump() returns the data as a string, which can be written into a file as well.

s = yaml.dump(d)

with open("data.yaml", "w") as f:
    f.write(s)

which again would produce the same file as above.


default_flow_style=None lets you mix styles:

print(yaml.dump(d, default_flow_style=None))
                   
A: a
B: {C: c, D: d, E: e}

while default_flow_style=True is straight up flow style:

print(yaml.dump(d, default_flow_style=True))
                   
{A: a, B: {C: c, D: d, E: e}}

Also, if you want to see valid kwargs of dump but help(yaml.dump) is not all too helpful, try help(yaml.dump_all) instead because dump is just a wrapper for dump_all.