如何用Python解析YAML文件

2024-04-20 03:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

使用Python 2+3(和unicode)读写YAML文件

# -*- coding: utf-8 -*-
import yaml
import io

# Define data
data = {
    'a list': [
        1, 
        42, 
        3.141, 
        1337, 
        'help', 
        u'€'
    ],
    'a string': 'bla',
    'another dict': {
        'foo': 'bar',
        'key': 'value',
        'the answer': 42
    }
}

# Write YAML file
with io.open('data.yaml', 'w', encoding='utf8') as outfile:
    yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)

# Read YAML file
with open("data.yaml", 'r') as stream:
    data_loaded = yaml.safe_load(stream)

print(data == data_loaded)

创建的YAML文件

a list:
- 1
- 42
- 3.141
- 1337
- help
- €
a string: bla
another dict:
  foo: bar
  key: value
  the answer: 42

通用文件结尾

.yml.yaml

替代品

对于您的应用程序,以下内容可能很重要:

  • 其他编程语言支持
  • 读写表现
  • 紧凑性(文件大小)

另请参见:Comparison of data serialization formats

如果您正在寻找创建配置文件的方法,那么您可能需要阅读我的短文Configuration files in Python

不依赖C头的最简单和最纯粹的方法是PyYaml(documentation):

#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

就这样。普通的yaml.load()函数也存在,但是yaml.safe_load()应该始终是首选函数,除非您明确需要提供任意对象序列化/反序列化,以避免引入任意代码执行的可能性。

注意PyYaml项目支持通过YAML 1.1 specification向上的版本。如果需要YAML 1.2 specification支持,请参见this answer中所述的ruamel.yaml

如果您有符合YAML 1.2 specification(2009年发布)的YAML,那么应该使用ruamel.yaml(免责声明:我是该包的作者)。 它本质上是PyYAML的一个超集,它支持YAML 1.1的大部分(从2005年开始)。

如果你想在往返旅行时保留你的评论,你当然应该使用ruamel.yaml。

升级@Jon的示例很简单:

import ruamel.yaml as yaml

with open("example.yaml") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

使用safe_load()除非您真正完全控制了输入,需要它(很少是这种情况)并知道您在做什么。

如果使用pathlibPath来操作文件,最好使用新的API ruamel.yaml提供:

from ruamel.yaml import YAML
from pathlib import Path

path = Path('example.yaml')
yaml = YAML(typ='safe')
data = yaml.load(path)

相关问题 更多 >