通过 Python 编辑 YAML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29518833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Editing YAML file by Python
提问by Tzimkiyahoo Bar Kozyva
I have a YAML file that looks like this:
我有一个看起来像这样的 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
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 ?
我想使用 Python 打开这个文件,更改一些值(见上文)并关闭文件。我怎样才能做到这一点 ?
For instance I want to set sense2[value]=1234, keeping the YAML output the same.
例如我想设置 sense2[value]=1234,保持 YAML 输出相同。
回答by jwilner
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)
回答by Anthon
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).
如果您关心保留映射键的顺序、注释和根级序列元素之间的空格,例如因为此文件受修订控制,那么您应该使用ruamel.yaml
(免责声明:我是该文件的作者)包裹)。
Assuming your YAML document is in the file input.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)
gives:
给出:
# 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