Skip to content

Instantly share code, notes, and snippets.

@rfinnie
Created September 3, 2021 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfinnie/eef4bb06edf2981649d458bf410e7443 to your computer and use it in GitHub Desktop.
Save rfinnie/eef4bb06edf2981649d458bf410e7443 to your computer and use it in GitHub Desktop.
import yaml
class YamlEdit:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
with open(self.filename) as f:
self.yaml_obj = yaml.safe_load(f)
return self.yaml_obj
def __exit__(self, exc_type, exc_val, exc_tb):
with open(self.filename, "w") as f:
yaml.dump(self.yaml_obj, f, default_flow_style=False)
if __name__ == "__main__":
with YamlEdit("file.yaml") as y:
y["foo"] = "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment