Python:
Werken met YAML
Hoe:
Om met YAML in Python te werken, heb je pyyaml nodig. Installeer het met:
pip install pyyamlLees een YAML-bestand:
import yaml
met open('config.yaml', 'r') als stream:
proberen:
config = yaml.safe_load(stream)
print(config)
behalve yaml.YAMLError als exc:
print(exc)Schrijf naar een YAML-bestand:
config = {'database': {'host': 'localhost', 'poort': 3306}}
met open('config.yaml', 'w') als bestand:
yaml.dump(config, bestand, default_flow_style=False)Zo ziet config.yaml eruit:
database:
host: localhost
poort: 3306Diepgaand
YAML werd gelanceerd in 2001 als een gebruiksvriendelijke gegevensserialisatiestandaard voor alle programmeertalen. JSON en XML zijn alternatieven, maar de focus van YAML op leesbaarheid is een opvallend kenmerk. Bij het parseren is safe_load cruciaal om willekeurige code-uitvoering te voorkomen vanwege onveilige YAML-inhoud. default_flow_style=False houdt de output niet JSON-achtig, waardoor de leesbaarheid van YAML behouden blijft.
Zie Ook
- Officiële PyYAML Documentatie: https://pyyaml.org/wiki/PyYAMLDocumentation
- YAML Specificatie: https://yaml.org/spec/1.2/spec.html
- Vergelijking tussen JSON en YAML: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/examples/data-serialization.pdf