使用 Python 读取 YAML 文件导致 yaml.composer.ComposerError: expected a single document in the stream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14359557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading YAML file with Python results in yaml.composer.ComposerError: expected a single document in the stream
提问by Sriharsha
I have a yaml file that looks like
我有一个 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
I am able to read this correctly in Perl using YAML but not in python using YAML. It fails with the error:
我可以使用 YAML 在 Perl 中正确读取它,但不能使用 YAML 在 python 中读取。它失败并出现错误:
expected a single document in the stream
预计流中只有一个文档
Program:
程序:
import yaml
stram = open("test", "r")
print yaml.load(stram)
Error:
错误:
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
采纳答案by Bonlenfum
The yaml documents are separated by ---, and if any stream (e.g. a file) contains more than one document then you should use the yaml.load_allfunction rather than yaml.load. The code:
yaml 文档由---,分隔,如果任何流(例如文件)包含多个文档,那么您应该使用该yaml.load_all函数而不是yaml.load. 编码:
import yaml
stream = open("test", "r")
docs = yaml.load_all(stream)
for doc in docs:
for k,v in doc.items():
print k, "->", v
print "\n",
results in for the input file as provided in the question:
结果为问题中提供的输入文件:
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

