Pavel Zagalsky Pavel Zagalsky - 1 year ago 149
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

I am using the 'yaml' package for Python.

Answer Source

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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download