A script that writes state.json directly and crashes halfway leaves a broken file behind. Writing to a temp file in the same folder and then swapping it in avoids that.
os.replace renames a file and overwrites the target if it exists:
import json, os, tempfile
def save(path, data):
folder = os.path.dirname(os.path.abspath(path))
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "w") as f:
json.dump(data, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
On POSIX systems the rename is atomic, so a reader sees the old file or the new file, never half of one. The fsync makes sure the data is on disk before the swap.
I’d use os.replace instead of os.rename because rename refuses to overwrite an existing file on Windows, while replace does it everywhere.
The temp file must be on the same filesystem as the target, which is why the example creates it in the same folder. Across filesystems the call fails instead of copying. Also, mkstemp gives the new file private permissions, so if other users need to read it, set the mode with os.chmod before the replace. And if the write raises, remove the temp file, or it stays behind.
Further reading: os.replace, tempfile.mkstemp