Library contents

Python open in exclusive mode

Create a new file only if its name is still available.

A simple example

open in exclusive mode

  1. Start with An unused name a.txt
  2. Do this Create exclusively twice
  3. Result First succeeds, second fails
The second attempt encounters the file created by the first.

Syntax

Python 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.py

Stop 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.

Resultalready issued
lesson.py
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")
Output
already issued

The second reservation identifies the existing name without overwriting its contents.

Advertisements

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?

GivenFile contents “clay”
Worked resultOriginal kept

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?

GivenFile contents “ring bell”
Worked resultOriginal kept

What to watch for

Checking for existence before creation opens a race. Use an atomic create-if-absent operation.

Documentation for open in exclusive mode