使用Python读取YAML文件时出现yaml.composer.ComposerError: expected a single document in the stream。

82

我有一个yaml文件,看起来像这样

---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341570
---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341569
---
level_1: "test"
level_2: 'NetApp, SOFS, ZFS Creation'
request: 341568

我能够使用YAML在Perl中正确读取这个内容,但是在使用YAML的Python中却不能。它会出现以下错误:

expected a single document in the stream

程序:

import yaml

stram = open("test", "r")
print yaml.load(stram)

错误:

Traceback (most recent call last):
  File "abcd", line 4, in <module>
    print yaml.load(stram)
  File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/__init__.py", line 58, in load
    return loader.get_single_data()
  File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/constructor.py", line 42, in get_single_data
    node = self.get_single_node()
  File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/composer.py", line 43, in get_single_node
    event.start_mark)
yaml.composer.ComposerError: expected a single document in the stream
  in "test", line 2, column 1
but found another document
  in "test", line 5, column 1

请参考http://www.yaml.org/spec/1.2/spec.html的第二章(语法)。它只需5分钟阅读,但非常值得。 - Titou
请参见如何在Python中解析YAML文件 - Martin Thoma
1个回答

128
yaml文档使用---进行分隔。如果任何一个流(例如文件)包含多个文档,则应该使用yaml.load_all函数而不是yaml.load。代码如下:
import yaml

stream = open("test", "r")
docs = yaml.load_all(stream, yaml.FullLoader)
for doc in docs:
    for k,v in doc.items():
        print k, "->", v
    print "\n",

以下是按照问题提供的输入文件产生的结果:

request -> 341570
level_1 -> test
level_2 -> NetApp, SOFS, ZFS Creation

request -> 341569
level_1 -> test
level_2 -> NetApp, SOFS, ZFS Creation

request -> 341568
level_1 -> test
level_2 -> NetApp, SOFS, ZFS Creation

31
这个答案可行。为了将来的参考,他们正在使用PyYAML模块,所以你必须要pip install pyyaml才能让它正常工作。 - wetjosh
4
根据https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation,建议使用`yaml.FullLoader`作为加载器,替代`yaml.load(stream, Loader=yaml.FullLoader)`。请仅供参考。 - cmhughes
1
还有yaml.safe_load_all(stream),它更适合加载你没有编写的.yml文件,因为它可以防止执行任意代码。 - Niko Pasanen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接