📦 什么是 YAML?
🔹 定义
YAML 是一种人类可读的数据序列化标准,语法简洁、易于阅读,常用于配置文件、Docker Compose、Kubernetes、GitHub Actions 等场景。
它使用缩进来表示层级关系,支持标量、列表、字典等数据结构,比如这样:
name: Alice
age: 25
is_student: false
skills:
- Python
- JavaScript
profile:
email: alice@example.com
city: Shanghai
🧪 Python 中使用 YAML(PyYAML 库)
✅ 1. Python 对象 → YAML 字符串(序列化)
import yaml
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "C++"]
}
yaml_str = yaml.dump(data, allow_unicode=True)
print(yaml_str)
输出:
age: 25
name: Alice
skills:
- Python
- C++
✅ 2. YAML 字符串 → Python 对象(反序列化)
yaml_input = """
name: Bob
age: 30
is_admin: false
"""
data = yaml.safe_load(yaml_input)
print(data["name"]) # 输出: Bob
✅ 3. 读写 YAML 文件
# 写入 YAML 文件
with open('data.yaml', 'w', encoding='utf-8') as f:
yaml.dump(data, f, allow_unicode=True)
# 从 YAML 文件读取
with open('data.yaml', 'r', encoding='utf-8') as f:
loaded_data = yaml.safe_load(f)
print(loaded_data)