From 0e81951f75271592c8ccd7c6644d5bfff540139c Mon Sep 17 00:00:00 2001 From: Marc Di Luzio Date: Fri, 16 Aug 2024 10:08:00 +0100 Subject: [PATCH] Ensure the path directory is created before saving a json file --- matchy/files/ops.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/matchy/files/ops.py b/matchy/files/ops.py index a076286..1c159b8 100644 --- a/matchy/files/ops.py +++ b/matchy/files/ops.py @@ -1,6 +1,8 @@ """File operation helpers""" import json import shutil +import pathlib +import os def load(file: str) -> dict: @@ -12,8 +14,12 @@ def load(file: str) -> dict: def save(file: str, content: dict): """ Save out a content dictionary to a file - Stores it in an intermediary file first incase the dump fails """ + # Ensure the save directory exists first + dir = pathlib.Path(os.path.dirname(file)) + dir.mkdir(parents=True, exist_ok=True) + + # Store in an intermediary directory first intermediate = file + ".nxt" with open(intermediate, "w") as f: json.dump(content, f, indent=4)