我有一个如下所示的 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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)