Install PyYAML (pip install pyyaml), open the file with UTF-8 encoding (open("config.yaml", "r", encoding="utf-8")), and call yaml.safe_load(f)—which safely parses YAML mappings, sequences, scalars, and dates into native Python dict, list, and primitive objects without risking arbitrary code execution.

Basic Example

from pathlib import Path
import yaml

config_path = Path("config.yaml")

# 1. Recommended: Read and parse a single-document YAML file safely
with open(config_path, "r", encoding="utf-8") as f:
    data = yaml.safe_load(f)

print(data)
# Example Output: {'app': {'name': 'worker', 'retries': 3, 'debug': False}}

# 2. Parse multi-document YAML files separated by `---`
with open("manifests.yaml", "r", encoding="utf-8") as f:
    documents = list(yaml.safe_load_all(f))  # Consume generator before closing file

Key Details & Edge Cases

  • Never use yaml.load(f) without Loader=yaml.SafeLoader (critical security vulnerability):
    • Calling yaml.load(f) with UnsafeLoader or FullLoader on untrusted YAML allows specially crafted tags (such as !!python/object/apply:os.system) to execute arbitrary Python code on your machine. Always use yaml.safe_load(f) (or yaml.load(f, Loader=yaml.SafeLoader)).
  • Empty YAML files return None (yaml.safe_load("") $\rightarrow$ None):
    • If a .yaml file is completely empty or contains only # comments, yaml.safe_load(f) returns None rather than {}. Normalize with data = yaml.safe_load(f) or {} when expecting a top-level dictionary.
  • Consume yaml.safe_load_all(f) inside the with open(...) block:
    • yaml.safe_load_all(f) returns a lazy generator, not a list. Iterating over it after exiting the with open(...) block raises ValueError: I/O operation on closed file. Always materialize it via list(yaml.safe_load_all(f)) while the file is still open.
  • YAML 1.1 implicit type quirks in PyYAML (NO, yes, on, 12:30):
    • PyYAML implements the YAML 1.1 specification, which parses unquoted yes, no, on, and off as booleans (True / False)—meaning an unquoted country code like country: NO (Norway) becomes False! Always quote strings like "NO" in YAML 1.1 files, or use ruamel.yaml when you need strict YAML 1.2 compliance and comment preservation.
  • Handling malformed YAML (yaml.YAMLError):
    • Tab characters used for indentation (YAML forbids tabs for indentation—spaces only) or mismatched colons raise yaml.YAMLError (with .problem_mark.line and .problem_mark.column attributes pinpointing the exact syntax error location).

Comparison of Python YAML Parsing Libraries & Functions

Library / Function Install Package YAML Spec Version Preserves Comments & Formatting on Round-Trip? Best Used When
yaml.safe_load(f) (Standard) pyyaml (import yaml) YAML 1.1 No Reading standard single-document YAML config files into Python dicts/lists.
yaml.safe_load_all(f) pyyaml (import yaml) YAML 1.1 No Parsing multi-document YAML streams separated by --- (e.g., Kubernetes manifests).
ruamel.yaml (YAML(typ="safe")) ruamel.yaml YAML 1.2 Yes (with default round-trip mode) Modifying YAML files programmatically without stripping comments, or enforcing YAML 1.2 rules.
strictyaml.load(text) strictyaml Restricted subset Yes Validating typed YAML schemas while blocking implicit type coercion (NO $\rightarrow$ False).