Search code examples
pythonpython-3.xyamlpyyaml

Load a YAML file and replace strings in resulting dictionary in Python


I have a YAML file that I currently load into a python object using pyyaml. I'm trying to figure out how to search and replace strings before returning the result.

def load_and_replace_yaml(directory, file_name):
    configs_path = os.path.join(directory, file_name) + '.yml'
    f = open(configs_path, 'r')
    overrides = yaml.safe_load(f.read())
    f.close()
    return overrides

So in the above code, I can get the yaml file as a file object, but I'm not sure how to do a find and replace on it. I could also try and do the find and replace on the resulting python dictionary overrides but I'm not sure how to search through the dictionary looking for strings to replace. Any help?


Solution

  • I realized that f.read() returns a string that I can just call replace() on before loading into yaml.safe_load.