如何在 Python 中解析 YAML 文件 [英] How can I parse a YAML file in Python

查看:78
本文介绍了如何在 Python 中解析 YAML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中解析 YAML 文件?

How can I parse a YAML file in Python?

推荐答案

不依赖 C 头文件的最简单、最纯粹的方法是 PyYaml (文档),可以通过pip install pyyaml安装:

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

#!/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() 应该总是首选,除非你明确需要提供的任意对象序列化/反序列化以避免引入了任意代码执行的可能性.

And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

请注意,PyYaml 项目支持通过 YAML 1.1 规范 的版本.如果需要YAML 1.2 规范支持,请参阅ruamel.yaml此答案中所述.

Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

这篇关于如何在 Python 中解析 YAML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆