Python open in exclusive mode
Create a new file only if its name is still available.
A simple example
open in exclusive mode
- Start with An unused name a.txt
- Do this Create exclusively twice
- Result First succeeds, second fails
Syntax
open(ticket, "x")
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyStop two desks claiming the same ticket
Two desks request the same claim number. Use exclusive creation for the second reservation so it cannot replace the first ticket, then report the collision to the clerk.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
ticket = base / "claim"
with ticket.open("x"):
pass
try:
with ticket.open("x"):
pass
except FileExistsError:
print("already issued")
already issued
The second reservation identifies the existing name without overwriting its contents.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
What to watch for
Checking for existence before creation opens a race. Use an atomic create-if-absent operation.