Search code examples
pythonyamlpyyaml

Changing a value in a yaml file using Python


I have a .yaml file I want to update with 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.


Solution

  • The problem is that yaml.dump(doc) doesn't actually write to a file. Instead, it returns the modified YAML as a string unless you pass the file descriptor as argument as well, which allows you to write directly to the file.

    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:
            yaml.dump(doc, f)