Python file handling
open() function
file not created
Python programming
error handling

Python open() does not create the file if it doesn't exist

Codemia Knowledge Hub ·

open() creates a file only in modes that allow creation: w, a, and x. Read modes such as r and r+ require the file to exist already. Separately, open() never creates missing parent directories, which is the other common reason a file fails to appear.

The mode decides whether a file is created

python
# This fails if the file does not already exist.
with open("example.txt", "r", encoding="utf-8") as f:
    print(f.read())
  • r: read only, file must exist
  • r+: read and write, file must exist
  • w: create if missing, truncate if present
  • a: create if missing, append if present
  • x: create only, fail if the file already exists

Binary variants such as wb or ab follow the same rules. The b changes text versus bytes handling, not whether the file is created.

Create, append, or create exclusively

Use w to create or overwrite:

python
with open("report.txt", "w", encoding="utf-8") as f:
    f.write("daily report\n")

Use a to keep existing content and add to it:

python
with open("report.txt", "a", encoding="utf-8") as f:
    f.write("another line\n")

Use x when creation must fail if the file is already there:

python
1try:
2    with open("config.ini", "x", encoding="utf-8") as f:
3        f.write("mode=production\n")
4except FileExistsError:
5    print("config.ini already exists")

x is often the safest choice for initialization code, where an accidental overwrite would be a bug. Picking the mode that matches the intent (w when replacing is fine, a for a growing log or history, x for exclusive first creation) also tells future readers what you meant.

Missing directories cause a different error

Even w or a fails if the parent directory does not exist. Create it first:

python
1from pathlib import Path
2
3path = Path("logs/app/output.txt")
4path.parent.mkdir(parents=True, exist_ok=True)
5
6with path.open("a", encoding="utf-8") as f:
7    f.write("started\n")

Developers often conclude that open() failed to create a file when the real problem was the missing directory tree.

Checking exists() first is racy

python
1from pathlib import Path
2
3path = Path("config.ini")
4if not path.exists():
5    with open(path, "w", encoding="utf-8") as f:
6        f.write("mode=production\n")

This is fine in tiny scripts, but in concurrent environments two processes can both see the file as missing and both create it. With x, the open call itself is the atomic decision point.

Writing critical files safely

Opening with w writes straight to the target path, so a crash mid-write can leave a truncated file. For important state:

  1. Write the new content to a temporary file.
  2. Flush and close it.
  3. Replace the old file atomically.

Many bugs blamed on open() are really about this update strategy, not about creation.

Mistakes to avoid

  • Expecting r or r+ to create a missing file. They do not.
  • Using w when the requirement was append-only or create-only behavior.
  • Forgetting that parent directories are not created automatically. A missing folder in the path makes open() fail even in w or a mode.
  • Checking exists() before creating a file when exclusive creation matters. Use x instead of a separate pre-check.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms