Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Python YAML

YAML

YAML - YAML Ain't Markup Language

Read YAML

  • load
  • Loader

# A comment

Course:
  Language:
    Name: Ladino
    IETF BCP 47: lad
  For speakers of:
    Name: English
    IETF BCP 47: en
  Special characters: []

Modules:
  - basic/
  - words/
  - verbs/
  - grammar/
  - names/
  - sentences/
import yaml

filename = "data.yaml"

with open(filename) as fh:
    data = yaml.load(fh, Loader=yaml.Loader)

print(data)

Write YAML

  • dump
  • Dumper
import yaml

filename = "out.yaml"

data = {
    "name": "Foo Bar",
    "children": ["Kid1", "Kid2", "Kid3"],
    "car": None,
    "code": 42,
}


with open(filename, 'w') as fh:
    yaml.dump(data, fh, Dumper=yaml.Dumper)

car: null
children:
- Kid1
- Kid2
- Kid3
code: 42
name: Foo Bar

Exercise: Counter in YAML

Exactly like the same exercise in the JSON chapter, but use a YAML file as the "database".

Exercise: Phone book in YAML

Exactly like the same exercise in the JSON chapter, but use a YAML file as the "database".

Solution: Counter in YAML

import sys
import os
import yaml

filename = "counter.yaml"

if len(sys.argv) > 2:
    exit(f"Usage: {sys.argv[0]} [NAME]")


counter = {}
if os.path.exists(filename):
    with open(filename) as fh:
        counter = yaml.load(fh, Loader=yaml.Loader)



if len(sys.argv) == 1:
    if counter:
        for key, value in counter.items():
            print("{key} {value}")
    else:
        print("No counters were found")
    exit()

name = sys.argv[1]

if name not in counter:
    counter[name] = 0
counter[name] += 1
print(counter[name])

with open(filename, 'w') as fh:
    yaml.dump(counter, fh, Dumper=yaml.Dumper)