KKitForma.

Language

EnglishEnglishTürkçeTurkishDeutschGermanGuide unavailable in this language · open toolsEspañolSpanishGuide unavailable in this language · open toolsFrançaisFrenchGuide unavailable in this language · open toolsPortuguêsPortugueseGuide unavailable in this language · open toolsItalianoItalianGuide unavailable in this language · open toolsNederlandsDutchGuide unavailable in this language · open toolsPolskiPolishGuide unavailable in this language · open toolsРусскийRussianGuide unavailable in this language · open toolsУкраїнськаUkrainianGuide unavailable in this language · open toolsSvenskaSwedishGuide unavailable in this language · open toolsNorskNorwegianGuide unavailable in this language · open toolsDanskDanishGuide unavailable in this language · open toolsSuomiFinnishGuide unavailable in this language · open toolsČeštinaCzechGuide unavailable in this language · open toolsRomânăRomanianGuide unavailable in this language · open toolsΕλληνικάGreekGuide unavailable in this language · open toolsالعربيةArabicGuide unavailable in this language · open toolsעבריתHebrewGuide unavailable in this language · open toolsفارسیPersianGuide unavailable in this language · open toolsاردوUrduGuide unavailable in this language · open toolsहिन्दीHindiGuide unavailable in this language · open toolsবাংলাBengaliGuide unavailable in this language · open toolsதமிழ்TamilGuide unavailable in this language · open toolsతెలుగుTeluguGuide unavailable in this language · open toolsमराठीMarathiGuide unavailable in this language · open toolsગુજરાતીGujaratiGuide unavailable in this language · open tools简体中文Chinese SimplifiedGuide unavailable in this language · open tools繁體中文Chinese TraditionalGuide unavailable in this language · open tools日本語JapaneseGuide unavailable in this language · open tools한국어KoreanGuide unavailable in this language · open toolsTiếng ViệtVietnameseGuide unavailable in this language · open toolsไทยThaiGuide unavailable in this language · open toolsBahasa IndonesiaIndonesianGuide unavailable in this language · open toolsBahasa MelayuMalayGuide unavailable in this language · open toolsFilipinoFilipinoGuide unavailable in this language · open toolsKiswahiliSwahiliGuide unavailable in this language · open toolsAfrikaansAfrikaansGuide unavailable in this language · open toolsMagyarHungarianGuide unavailable in this language · open toolsБългарскиBulgarianGuide unavailable in this language · open toolsHrvatskiCroatianGuide unavailable in this language · open toolsSrpskiSerbianGuide unavailable in this language · open toolsSlovenčinaSlovakGuide unavailable in this language · open toolsSlovenščinaSlovenianGuide unavailable in this language · open toolsLietuviųLithuanianGuide unavailable in this language · open toolsLatviešuLatvianGuide unavailable in this language · open toolsEestiEstonianGuide unavailable in this language · open toolsCatalàCatalanGuide unavailable in this language · open toolsEuskaraBasqueGuide unavailable in this language · open tools
← Questions & answers

KITFORMA · EDITORIAL ANSWER

How do I avoid leaving a partially written JSON configuration file?

KitForma editorial guide. Write JSON to a temporary sibling, close it, and replace the destination only after serialization succeeds.

Python →

Step-by-step answer

Opening the destination with mode w truncates it before serialization finishes. A temporary sibling keeps the previous file intact until a complete replacement is ready. This example injects a failure before replacement and runs only in a temporary directory. Runnable example:
python
import json
import os
import tempfile
from pathlib import Path

def save_json(path, value, fail_before_replace=False):
    pending = None
    try:
        with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
                dir=path.parent, delete=False) as handle:
            pending = Path(handle.name)
            json.dump(value, handle, allow_nan=False)
            handle.flush()
            os.fsync(handle.fileno())
        if fail_before_replace:
            raise RuntimeError("Injected failure")
        os.replace(pending, path)
    finally:
        if pending is not None:
            pending.unlink(missing_ok=True)

with tempfile.TemporaryDirectory() as directory:
    path = Path(directory) / "config.json"
    path.write_text('{"version":1}', encoding="utf-8")
    try:
        save_json(path, {"version": 2}, fail_before_replace=True)
    except RuntimeError:
        pass
    print(json.loads(path.read_text(encoding="utf-8"))["version"])
    save_json(path, {"version": 2})
    print(json.loads(path.read_text(encoding="utf-8"))["version"])
Expected result:
text
1
2
Why it works: The temporary file is placed beside the destination, avoiding a cross-filesystem move. Closing it before os.replace also avoids keeping the temporary handle open during replacement on Windows. Serialization failure and the injected failure leave the old destination untouched; finally removes only this operation’s temporary path. Scope and checks: Python 3.12 or later; checked against Python 3.14 os.replace documentation. Atomic replacement depends on filesystem and operating-system behavior. File fsync alone is not a complete power-loss durability protocol; directory synchronization may be needed. The temporary file’s permissions become the replacement’s permissions. Multi-writer locking, intended ACLs and schema validation remain application responsibilities. Related tools and guides: Validate a JSON sample before saving: https://kitforma.com/en/json-formatter/ Non-finite numbers in Python JSON: https://kitforma.com/en/community/questions/7aa10000-0000-4000-8000-000000007380/ Primary sources (reviewed 2026-10-08): Python 3.14 — os.replace: https://docs.python.org/3.14/library/os.html#os.replace Python 3.14 — NamedTemporaryFile: https://docs.python.org/3.14/library/tempfile.html#tempfile.NamedTemporaryFile

Sources and verification

Sources checked:

This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.

Discussion and community answers

Loading community…
KitForma

What would you like to do?