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

open in Python does not create a file if it doesn't exist

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python's open() can create a file, but only in modes that allow creation. Most confusion comes from using a read-oriented mode such as r or r+ and expecting a missing file to appear automatically, when file creation and directory creation are separate behaviors.

File Mode Controls Creation

The behavior of open() depends almost entirely on the mode string.

python
# This fails if the file does not already exist.
with open("example.txt", "r", encoding="utf-8") as f:
    print(f.read())

The most important text modes are:

  • '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'

The same creation rules apply to binary variants such as wb or ab. The b changes text-versus-bytes handling, not the creation policy.

Create a File Intentionally

If you want to create or overwrite a file, use w.

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

If you want to preserve existing content and append new data, use a.

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

If you want creation to fail when the file is already present, use x.

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")

That is often the safest option for initialization code where accidental overwrite would be a bug.

Missing Directories Are a Different Problem

Even a creation-capable mode will fail if the parent directory does not exist.

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")

This distinction matters because developers often conclude that open() failed to create a file when the real error is that the directory tree was missing.

Choose the Mode Based on Intent

A good rule is to pick the mode that matches the business rule, not just the one that "works":

  • use w when replacing the file is acceptable
  • use a when the file is a growing log or history
  • use x when first creation must be exclusive

That keeps file behavior self-documenting. A future reader can infer whether overwrite, append, or create-only semantics were intended.

Avoid Race-Prone Create Logic

A common anti-pattern is to check for existence first and then open the file.

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 acceptable in tiny scripts, but in concurrent environments it is racy. Two processes can both observe that the file is missing and then both attempt creation.

If you need exclusive creation semantics, x is better because the open call itself becomes the atomic decision point.

Think About Safe Writes Too

File creation is only part of correct file handling. If the file contains important state, opening with w writes directly to the target path and can leave a truncated file if the process crashes mid-write.

A safer pattern for critical state is:

  1. write the new content to a temporary file
  2. flush and close it
  3. replace the old file atomically

That is beyond the narrow question of creation, but it matters because many bugs blamed on open() are really about update strategy and overwrite safety.

Common Pitfalls

The most common mistake is expecting r or r+ to create a missing file. They do not. Another is using w when the real requirement was append-only or create-only behavior.

Developers also often forget that parent directories are not created automatically. If the path includes a missing folder, open() still fails even in w or a mode.

Finally, checking exists() before creating a file can introduce race conditions. If exclusive creation matters, use x instead of a separate pre-check.

Summary

  • 'open() can create files, but only in creation-capable modes such as w, a, and x.'
  • 'r and r+ require the file to already exist.'
  • Parent directories must be created separately.
  • Choose the mode that matches your overwrite, append, or create-only intent.
  • For critical files, think beyond creation and design a safe write strategy too.

Course illustration
Course illustration

All Rights Reserved.