Python FileExistsError
Opening a file in exclusive creation mode rejects an existing report.
A simple example
FileExistsError
- Start with A file named a.txt already exists
- Do this Try exclusive creation at the same name
- Result Creation fails
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.pySave 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 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")
Choose a new report name
The exclusive create sees the existing report. Its earlier contents are preserved.
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.
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.
What to watch for
Use the exclusive open itself for the decision. A separate existence check leaves a gap before creation.