I have a yaml file that looks like
JavaScript
x
13
13
1
---
2
level_1: "test"
3
level_2: 'NetApp, SOFS, ZFS Creation'
4
request: 341570
5
---
6
level_1: "test"
7
level_2: 'NetApp, SOFS, ZFS Creation'
8
request: 341569
9
---
10
level_1: "test"
11
level_2: 'NetApp, SOFS, ZFS Creation'
12
request: 341568
13
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:
JavaScript
1
5
1
import yaml
2
3
stram = open("test", "r")
4
print yaml.load(stram)
5
Error:
JavaScript
1
14
14
1
Traceback (most recent call last):
2
File "abcd", line 4, in <module>
3
print yaml.load(stram)
4
File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/__init__.py", line 58, in load
5
return loader.get_single_data()
6
File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/constructor.py", line 42, in get_single_data
7
node = self.get_single_node()
8
File "/usr/local/pkgs/python-2.6.5/lib/python2.6/site-packages/yaml/composer.py", line 43, in get_single_node
9
event.start_mark)
10
yaml.composer.ComposerError: expected a single document in the stream
11
in "test", line 2, column 1
12
but found another document
13
in "test", line 5, column 1
14
Advertisement
Answer
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:
JavaScript
1
9
1
import yaml
2
3
stream = open("test", "r")
4
docs = yaml.load_all(stream, yaml.FullLoader)
5
for doc in docs:
6
for k,v in doc.items():
7
print k, "->", v
8
print "n",
9
results in for the input file as provided in the question:
JavaScript
1
12
12
1
request -> 341570
2
level_1 -> test
3
level_2 -> NetApp, SOFS, ZFS Creation
4
5
request -> 341569
6
level_1 -> test
7
level_2 -> NetApp, SOFS, ZFS Creation
8
9
request -> 341568
10
level_1 -> test
11
level_2 -> NetApp, SOFS, ZFS Creation
12