Tzimkiyahoo Bar Kozyva
Tzimkiyahoo Bar Kozyva

Reputation: 311

Editing YAML file by Python

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.

Upvotes: 31

Views: 82245

Answers (3)

Ahmed Taha Hagag
Ahmed Taha Hagag

Reputation: 27

This script allows you to update specific fields in a YAML file by providing field-value pairs as command-line arguments.

https://github.com/ataha/python-snippets/blob/master/YAML_modifier/YAML_Modifier.py

Upvotes: 0

Anthon
Anthon

Reputation: 76862

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).

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)

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

This can safely be used on untrusted YAML. The (default) RoundtripLoader is a subclass of the SafeLoader even though it can handle and preserve tags (which it doesn't interpret in the dangerous way PyYAML does when enabling loading of unregistered tags).

Upvotes: 43

jwilner
jwilner

Reputation: 6606

import yaml

with open("data.yaml") as f:
     list_doc = yaml.safe_load(f)

for sense in list_doc:
    if sense["name"] == "sense2":
         sense["value"] = 1234

with open("data.yaml", "w") as f:
    yaml.dump(list_doc, f)

Upvotes: 35

Related Questions