"""Copyright (c) 2025 MPI-M, Clara Bayley----- CLEO -----File: editconfigfile.pyProject: cleopyCreated Date: Wednesday 17th January 2024Author: Clara Bayley (CB)Additional Contributors:-----License: BSD 3-Clause "New" or "Revised" Licensehttps://opensource.org/licenses/BSD-3-Clause-----File Description:"""fromruamel.yamlimportYAML
[docs]defupdate_param(node,param,new_value):"""Function to recursively searches for 'param' key in YAML node and updates it's value to with 'new_value' when found"""ifisinstance(node,dict):ifparaminnode:node[param]=new_value# update valuereturnTrueelse:forkey,valinnode.items():is_success=update_param(val,param,new_value)ifis_success:returnTrueelifisinstance(node,list):foriteminnode:is_success=update_param(item,param,new_value)ifis_success:returnTruereturnFalse
[docs]defedit_config_params(filename,params2change):"""rewrites config YAML file with key,value pairs listed in params2change updated to new values whilst preserving original YAML file's formatting and comments etc."""yaml=YAML()# Load the YAML filewithopen(filename,"r")asfile:data=yaml.load(file)# Update the parameters from the YAML fileforparam,new_valueinparams2change.items():is_success=update_param(data,param,new_value)ifnotis_success:errmsg=param+" could not be updated to new value: "+str(new_value)raiseValueError(errmsg)# Overwrite the YAML filewithopen(filename,"w")asfile:yaml.dump(data,file)