用 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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)