使用 Python 读取 YAML 文件会导致 yaml.composer.ComposerError: expected a single document in the stream

编程入门 行业动态 更新时间:2024-10-28 11:29:55
问题描述

我有一个看起来像这样的 yaml 文件

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

我能够在使用 YAML 的 Perl 中正确读取此内容,但在使用 YAML 的 python 中无法正确读取.它失败并出现错误:

I am able to read this correctly in Perl using YAML but not in python using YAML. It fails with the error:

预期流中有单个文档

程序:

import yamlstram = 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)yamlposer.ComposerError: expected a single document in the stream in "test", line 2, column 1but found another document in "test", line 5, column 1

推荐答案

yaml 文档用 --- 分隔,如果任何流(例如文件)包含多个文档,那么你应该使用 yaml.load_all 函数而不是 yaml.load.代码:

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 yamlstream = open("test", "r")docs = yaml.load_all(stream)for doc in docs: for k,v in doc.items(): print k, "->", v print "",

问题中提供的输入文件的结果:

results in for the input file as provided in the question:

request -> 341570level_1 -> testlevel_2 -> NetApp, SOFS, ZFS Creationrequest -> 341569level_1 -> testlevel_2 -> NetApp, SOFS, ZFS Creationrequest -> 341568level_1 -> testlevel_2 -> NetApp, SOFS, ZFS Creation
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

使用 Python 读取 YAML 文件会导致 yaml.composer.ComposerError: expected a single document

本文发布于:2023-05-22 18:52:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!