2013-01-16 97 views
35

我有一個YAML文件看起來像閱讀YAML在python

--- 
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不是在蟒蛇。它失敗,出現錯誤:

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 
+0

對於參考文獻參見http://www.yaml.org/spec/1.2的第2章(語法) /spec.html。這是一個5分鐘的閱讀和值得。 – Titou

+0

請參閱[如何使用Python解析YAML文件](https://stackoverflow.com/a/42054860/562769) –

回答

58

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 
+17

此答案適用。對於將來的後代,他們使用PyYAML模塊,所以你必須'pip安裝pyyaml'才能工作。 – wetjosh