简体   繁体   English

无法将 yaml 文件解析为 python

[英]Unable to parse yaml file into python

I am trying to parse data from a simple YAML file into python however running the program generates an error.我正在尝试将简单 YAML 文件中的数据解析为 python 但是运行程序会产生错误。

File.py文件.py

#!/usr/bin/env python3 #!/usr/bin/env python3

import yaml进口 yaml

with open ('xyz.yml', 'r') as handle:以 open ('xyz.yml', 'r') 作为句柄:

try:
    print("File opened")
    data = yaml.full_load(handle)
    print("data loaded")
    print(data)
except yaml.YAMLError as error:
    print(error)

YAML file contains as below. YAML 文件包含以下内容。

xyz.yml xyz.yml


name: nick # YAML allows comments things: -chair -table名称:nick #YAML 允许评论事物:-chair -table

  • sofa: color: gray age: 2沙发:颜色:灰色年龄:2

However, running the program但是,运行程序

➜ PYTHON python3 file.py File opened mapping values are not allowed here in "xyz.yml", line 9, column 9 ➜ PYTHON python3 file.py 在“xyz.yml”第9行第9列中不允许打开文件映射值

Anything wrong with syntax or code?语法或代码有什么问题吗? The same data works with JSON.相同的数据适用于 JSON。 I have tried the same code with JSON Data, of course with JSON structure data and loading the JSON library and necessary JSON calls in the python program I have tried the same code with JSON Data, of course with JSON structure data and loading the JSON library and necessary JSON calls in the python program

The problem here is with your YAML file I believe, it should've been:这里的问题是您的 YAML 文件,我相信它应该是:

name: nick # YAML allows comments
things:
  - chair
  - table
  - sofa:
      color: gray
      age: 2

YAML depends a lot on indentation so keep that in mind. YAML 很大程度上取决于缩进,所以请记住这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM