1

I have a yaml file and want to change few parameters of the same file temp.yaml.

%YAML 1.2
---
name: first
cmp:
- Some: first
  top:
    top_rate: 16000
    audio_device: "pulse"

---
name: second
components:
- name: second
  parameters:
    always_on: true
    timeout: 200000

I am able to open the file using yaml.load_all But how can I modify and dump data into same file. There is a method dump_all but am unsure of it's usage.

import yaml

with open('temp.yaml') as f:
    temp = yaml.safe_load_all(f)
    for t in temp:
        if t['name'] == 'first':
            t['cmp'][0]['Some'] = 'Result'
        if t['name'] == 'second':
            t['components']['parameters']['always_on'] = False

How can I dump it back to temp.yaml. So that it look like

%YAML 1.2
---
name: first
cmp:
- Some: Result
  top:
    top_rate: 16000
    audio_device: "pulse"

---
name: second
components:
- name: second
  parameters:
    always_on: false
    timeout: 200000
Pranjal Doshi
  • 862
  • 11
  • 29

1 Answers1

0

Use 'r+':

with open('temp.yaml', 'r+') as f:
    temp = yaml.safe_load_all(f)
    for t in temp:
        if t['name'] == 'first':
            t['cmp'][0]['Some'] = 'Result'
        if t['name'] == 'second':
            t['components']['parameters']['always_on'] = False
    # reset to position 0
    f.seek(0)
    yaml.safe_dump_all(test, f)
    # if new file is shorter than original file, truncate additional bytes
    f.truncate()

Mind that empty lines will not be preserved as they are discarded by the YAML parser. Quoted scalars like "pulse" will become unquoted because the information about quotation is lost when loading the data into native structures.

For more information about preserving style, check this question.

flyx
  • 35,506
  • 7
  • 89
  • 126