Editing YAML file by Python

Tzimkiyahoo Bar Kozyva picture Tzimkiyahoo Bar Kozyva · Apr 8, 2015 · Viewed 31.4k times · Source

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

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 ?

For instance I want to set sense2[value]=1234, keeping the YAML output the same.

Answer

jwilner picture jwilner · Apr 8, 2015
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)