读取YAML文件与Python导致yaml.composer.ComposerError:流预期单个

2019-07-18 06:38发布

我有一个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

我能够在Perl正确地阅读本使用YAML,但使用YAML不是在蟒蛇。 它失败,出现错误:

预期单个文档在流中

程序:

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

Answer 1:

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",

导致了在这一问题提供的输入文件:

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


文章来源: Reading YAML file with Python results in yaml.composer.ComposerError: expected a single document in the stream