用 Python 编辑 YAML 文件

Editing YAML file by Python(用 Python 编辑 YAML 文件)

本文介绍了用 Python 编辑 YAML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 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 sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True
with 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 further
yaml.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

这篇关于用 Python 编辑 YAML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:用 Python 编辑 YAML 文件

基础教程推荐