Pavel Zagalsky Pavel Zagalsky - 13 days ago 5
Python Question

Changing a value in a yaml file using Python

I have a .yaml file I want to update with a Python code.
Let's say it looks something like that:

state: 'present'


I'd like to have a code that changes the state and saves the file.
I'm trying with something like this and fail:

def set_state(state):
with open("file_to_edit.yaml", 'rw') as f:
doc = yaml.load(f)
doc['state'] = state
yaml.dump(f)


I am using the 'yaml' package for Python.
Thanks!!

Answer

The problem is that yaml.dump don't actually write to a file. Instead, it returns the modified YAML structure.

The following should work:

def set_state(state):
    with open('file_to_edit.yaml') as f:
        doc = yaml.load(f)

    doc['state'] = state

    with open('file_to_edit.yaml', 'w') as f:
        f.write(yaml.dump(doc))