如何将 YAML 文件解析/读取到 Python 对象中?

编程入门 行业动态 更新时间:2024-10-27 23:20:01
问题描述

如何将 YAML 文件解析/读取到 Python 对象中?

How to parse/read a YAML file into a Python object?

例如,这个 YAML:

For example, this YAML:

Person: name: XYZ

到这个 Python 类:

To this Python class:

class Person(yaml.YAMLObject): yaml_tag = 'Person' def __init__(self, name): self.name = name

顺便说一句,我正在使用 PyYAML.

I am using PyYAML by the way.

推荐答案

如果你的 YAML 文件如下所示:

If your YAML file looks like this:

# tree formattreeroot: branch1: name: Node 1 branch1-1: name: Node 1-1 branch2: name: Node 2 branch2-1: name: Node 2-1

你已经像这样安装了 PyYAML:

And you've installed PyYAML like this:

pip install PyYAML

Python 代码如下所示:

And the Python code looks like this:

import yamlwith open('tree.yaml') as f: # use safe_load instead load dataMap = yaml.safe_load(f)

变量 dataMap 现在包含一个带有树数据的字典.如果你使用 PrettyPrint 打印 dataMap,你会得到类似的东西:

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{ 'treeroot': { 'branch1': { 'branch1-1': { 'name': 'Node 1-1' }, 'name': 'Node 1' }, 'branch2': { 'branch2-1': { 'name': 'Node 2-1' }, 'name': 'Node 2' } }}

所以,现在我们已经了解了如何将数据导入 Python 程序.保存数据同样简单:

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f: yaml.dump(dataMap, f)

你有一本字典,现在你必须把它转换成一个 Python 对象:

You have a dictionary, and now you have to convert it to a Python object:

class Struct: def __init__(self, **entries): self.__dict__.update(entries)

那么你可以使用:

>>> args = your YAML dictionary>>> s = Struct(**args)>>> s<__main__.Struct instance at 0x01D6A738>>>> s...

并遵循将 Python dict 转换为对象".

有关更多信息,您可以查看 pyyaml 和 这个.

For more information you can look at pyyaml and this.

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

如何将 YAML 文件解析/读取到 Python 对象中?

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

发布评论

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

>www.elefans.com

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