Python解析YAML文件

文章目录

  • Python解析YAML文件
    • 安装PyYAML
    • 基本使用方法
      • 1. 读取YAML文件
      • 2. 写入YAML文件
    • 示例YAML文件
    • 解析示例
    • 高级功能
      • 1. 加载多个文档
      • 2. 自定义标签
    • 安全注意事项
    • 替代库

Python解析YAML文件

YAML是一种人类友好的数据序列化格式,Python中可以使用PyYAML库来解析和生成YAML文件。

安装PyYAML

首先需要安装PyYAML库:

pip install pyyaml

基本使用方法

1. 读取YAML文件

import yaml

with open('example.yaml', 'r', encoding='utf-8') as file:
    data = yaml.safe_load(file)

print(data)

2. 写入YAML文件

import yaml

data = {
    'name': 'John Doe',
    'age': 30,
    'skills': ['Python', 'YAML', 'JSON']
}

with open('output.yaml', 'w', encoding='utf-8') as file:
    yaml.dump(data, file, default_flow_style=False, allow_unicode=True)

示例YAML文件

假设有一个config.yaml文件:

database:
  host: localhost
  port: 3306
  username: admin
  password: secret
  databases:
    - main
    - backup

servers:
  web:
    - host: web1.example.com
      port: 80
    - host: web2.example.com
      port: 8080
  db:
    - host: db1.example.com
      port: 3306

解析示例

import yaml

with open('config.yaml', 'r', encoding='utf-8') as file:
    config = yaml.safe_load(file)

# 访问数据
print(f"Database host: {config['database']['host']}")
print(f"Web servers:")
for server in config['servers']['web']:
    print(f"  - {server['host']}:{server['port']}")

高级功能

1. 加载多个文档

YAML文件可以包含多个文档,用---分隔:

documents = """
---
name: Document 1
value: 123
---
name: Document 2
value: 456
"""

for data in yaml.safe_load_all(documents):
    print(data)

2. 自定义标签

PyYAML支持自定义标签:

def construct_my_object(loader, node):
    value = loader.construct_scalar(node)
    return f"MyObject: {value}"

yaml.add_constructor('!myobj', construct_my_object)

data = yaml.safe_load("""
example: !myobj example_value
""")

print(data)  # {'example': 'MyObject: example_value'}

安全注意事项

  • 使用safe_load()而不是load()来避免潜在的安全风险
  • 不要加载不受信任的YAML文件,因为它们可能包含恶意代码

替代库

如果需要更高级的功能,可以考虑:

  • ruamel.yaml - 支持YAML 1.2,保留注释和顺序
  • oyaml - 保持字典顺序的YAML库

希望这个指南能帮助你开始使用Python解析YAML文件!

你可能感兴趣的:(Python,python)