我有一个YAML文件,如下所示:
# 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打开这个文件,更改一些值(见上文)并关闭文件。我怎么能这样做?
例如我想设置sense2 [value] = 1234,保持YAML输出相同。
答案 0 :(得分:10)
with open("my_file.yaml") as f:
list_doc = yaml.load(f)
for sense in list_doc:
if sense["name"] == "sense2":
sense["value"] = 1234
with open("my_file.yaml", "w") as f:
yaml.dump(list_doc, f)
答案 1 :(得分:6)
如果您关心保留映射键的顺序,则根级序列的元素之间的注释和空格,例如,因为此文件受版本控制,所以您应该使用ruamel.yaml
(免责声明:我是该软件包的作者)。
假设您的YAML文档位于文件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