81

I have a yaml file that looks like

---
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:

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
finefoot
  • 9,914
  • 7
  • 59
  • 102
Sriharsha
  • 2,373
  • 1
  • 16
  • 20

1 Answers1

127

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_all function rather than yaml.load. The code:

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

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
y ramesh rao
  • 2,954
  • 4
  • 25
  • 39
Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
  • 31
    This answer works. For future posterity, they are using the PyYAML module, so you must `pip install pyyaml` for it to work. – wetjosh Apr 13 '16 at 16:48
  • 4
    just for reference: according to https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation `yaml.load(stream, Loader=yaml.FullLoader)` is recommended – cmhughes Apr 19 '19 at 11:39
  • 1
    There's also `yaml.safe_load_all(stream)` which is better for loading .yml files that you've not written yourself, as it prevents executing arbitrary code. – Niko Föhr Apr 05 '23 at 07:05