Batu Lab NotesPractical developer guides

Keep JSON CSV reports from overwriting an existing file

By Batu ยท English technical notes

Also published in our Blogger archive.

Quick answer

Path.open accepts the same exclusive x mode as built-in open: creation fails when the target already exists.

Example

The fixture writes an old report, attempts open("x"), catches FileExistsError, and rereads the original text. The assertion proves the exclusive attempt did not replace the existing artifact.

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    p = Path(d) / 'report.json'
    p.write_text('old')
    try:
        p.open('x').close()
    except FileExistsError:
        outcome = 'exists'
    assert p.read_text() == 'old' and outcome == 'exists'
    print(outcome)

Expected stdout:

exists

Reading the result

Exclusive creation does not choose a safe path for the caller and does not solve permission errors. Handle those outcomes separately rather than treating every write failure as a collision.

For JSON reports, write content only after exclusive creation succeeds. Opening an existing file in ordinary write mode first would defeat the safety boundary before serialization is even considered.

The attempted write is intentionally empty because the point is the creation boundary. Serialize the report only inside the block that follows a successful exclusive open.

Sources

- Python pathlib documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.