Editing YAML file by Python(用 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 文件
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
