用 Python 编辑 YAML 文件

编程入门 行业动态 更新时间:2024-10-27 17:19:34
问题描述

我有一个如下所示的 YAML 文件:

I have a YAML file that looks like this:

# Sense 1- name : sense1 type : float value : 31# sense 2- name : sense2 type : uint32_t value : 1488# Sense 3- name : sense3 type : int32_t value : 0- name : sense4 type : int32_t value : 0- name : sense5 type : int32_t value : 0- name : sense6 type : int32_t value : 0

我想使用 Python 打开这个文件,更改一些值(见上文)并关闭文件.我该怎么做?

I want to use Python to open this file, change some of the values (see above) and close the file. How can I do that ?

例如我想设置 sense2[value]=1234,保持 YAML 输出不变.

For instance I want to set sense2[value]=1234, keeping the YAML output the same.

推荐答案

如果您关心保留映射键的顺序、注释和根级序列元素之间的空格,例如因为此文件受修订控制,所以您应该使用 ruamel.yaml (免责声明:我是该软件包的作者).

If you care about preserving the order of your mapping keys, the comment and the white space between the elements of the root-level sequence, e.g. because this file is under revision control, then you should use ruamel.yaml (disclaimer: I am the author of that package).

假设您的 YAML 文档在文件 input.yaml 中:

Assuming your YAML document is in the file input.yaml:

import sysimport ruamel.yamlyaml = ruamel.yaml.YAML()# yaml.preserve_quotes = Truewith open('input.yaml') as fp: data = yaml.load(fp)for elem in data: if elem['name'] == 'sense2': elem['value'] = 1234 break # no need to iterate furtheryaml.dump(data, sys.stdout)

给予:

# Sense 1- name: sense1 type: float value: 31# sense 2- name: sense2 type: uint32_t value: 1234# Sense 3- name: sense3 type: int32_t value: 0- name: sense4 type: int32_t value: 0- name: sense5 type: int32_t value: 0- name: sense6 type: int32_t value: 0
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

用 Python 编辑 YAML 文件

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

发布评论

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

>www.elefans.com

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