Create a new local report without replacing an existing file
Also published in our Blogger archive.
Quick answer
Path.open with mode x creates a text file only when no directory entry already exists at that path.
Example
The example writes report once, then attempts the same exclusive creation and expects FileExistsError. Reading the file afterward proves the original content remains available for review.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
p = Path(d) / 'new.txt'
with p.open('x', encoding='utf-8') as f:
f.write('report')
try:
p.open('x').close()
except FileExistsError:
again = 'blocked'
assert p.read_text() == 'report' and again == 'blocked'
print(again)
Expected stdout:
blocked
Reading the result
This guard is local to the final path. It does not make a report directory trustworthy, coordinate multiple report names, or handle a missing parent directory.
When a collision occurs, return the existing path in the diagnostic but do not read or display its contents by default. Existence is enough to explain why creation was blocked.
The second attempt is the failure case and the first write is the normal case. Both are needed to show that x has a useful contract rather than merely raising an exception.
Sources
- Python pathlib documentation
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.