在Python中解析YAML文件并访问数据?

9mo*_*eys 74 python xml parsing yaml

我是YAML的新手,一直在寻找解析YAML文件和使用/访问解析后的YAML数据的方法.

我遇到了关于如何解析YAML文件的解释,例如,PyYAML 教程," 我如何在Python中解析YAML文件 "," 将Python dict转换为对象? ",但我没有找到的是关于如何从解析的YAML文件访问数据的简单示例.

假设我有一个YAML文件,例如:

 treeroot:
     branch1: branch1 text
     branch2: branch2 text
Run Code Online (Sandbox Code Playgroud)

如何访问"branch1 text"文本?

" YAML解析和Python? "提供了一个解决方案,但是我在从更复杂的YAML文件访问数据时遇到了问题.而且,我想知道是否有一些标准的方法从解析的YAML文件访问数据,可能类似于" 树迭代 "或" 元素路径 "符号或解析XML文件时将使用的东西?

Aph*_*hex 140

由于PyYAML的yaml.load()函数将YAML文档解析为本机Python数据结构,因此您只需按键或索引访问项目即可.使用您链接的问题中的示例:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)
Run Code Online (Sandbox Code Playgroud)

要访问branch1 text您将使用:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
Run Code Online (Sandbox Code Playgroud)

因为,在您的YAML文档中,branch1键的值在键下treeroot.

  • 我得到"TypeError:字符串索引必须是整数,而不是str".似乎我不能使用字符串作为索引. (2认同)

小智 5

仅供参考@Aphex 的解决方案 -

如果您遇到 - “ YAMLLoadWarning: call yaml.load() without Loader=... is deprecated ”,您可能需要使用 Loader=yaml.FullLoader 或 yaml.SafeLoader 选项。

import yaml 

with open('cc_config.yml', 'r') as f:
    doc = yaml.load(f, Loader=yaml.FullLoader) # also, yaml.SafeLoader

txt = doc["treeroot"]["branch1"]
print (txt)
Run Code Online (Sandbox Code Playgroud)