Library contents

Python FileExistsError

Opening a file in exclusive creation mode rejects an existing report.

A simple example

FileExistsError

  1. Start with A file named a.txt already exists
  2. Do this Try exclusive creation at the same name
  3. Result Creation fails
Exclusive creation protects the existing file from replacement.

Syntax

Python syntax
path.open("x")
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Save a report without replacing the first copy

Two shifts try to save their report under the same filename. The second shift needs to learn that the name is taken while the first shift's report stays available.

From the programreport.write_text("First shift", encoding="utf-8")
ResultChoose a new report name
lesson.py
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    report = Path(folder) / "shift.txt"
    report.write_text("First shift", encoding="utf-8")
    try:
        with report.open("x", encoding="utf-8") as new_report:
            new_report.write("Second shift")
    except FileExistsError:
        print("Choose a new report name")
Output
Choose a new report name

The exclusive create sees the existing report. Its earlier contents are preserved.

Advertisements

Issue the first parcel claim

The counter opens a new workspace for today’s pickup. Create the claim file exclusively so that an existing claim stays intact.

GivenUnused name
Worked resultClaim created

Preserve a previous reservation

The second counter tries a name already reserved by the first counter. Create the claim file exclusively so that an existing claim stays intact.

GivenExisting claim
Worked resultKeep earlier claim

What to watch for

Use the exclusive open itself for the decision. A separate existence check leaves a gap before creation.

Documentation for FileExistsError