FileExistsError
PythonERRORCommonOS ErrorHIGH confidence

File or directory already exists

Production Risk

Use exist_ok=True for idempotent directory creation in deployment scripts.

What this means

A subclass of OSError (errno EEXIST) raised when trying to create a file or directory that already exists.

Why it happens
  1. 1os.mkdir() on a directory that already exists
  2. 2open() with mode "x" (exclusive creation) on an existing file
  3. 3os.link() creating a hard link that already exists
How to reproduce

mkdir() on an existing directory.

trigger — this will error
trigger — this will error
import os
os.mkdir('/tmp')  # /tmp already exists

expected output

FileExistsError: [Errno 17] File exists: '/tmp'

Fix 1

Use exist_ok=True with makedirs

WHEN Creating directories that may already exist

Use exist_ok=True with makedirs
import os
os.makedirs('/path/to/dir', exist_ok=True)  # No error if exists

Why this works

exist_ok=True makes makedirs() silently succeed if the directory already exists.

Fix 2

Use exclusive file creation safely

WHEN Creating a file that must not already exist

Use exclusive file creation safely
try:
    with open('lockfile', 'x') as f:
        f.write(str(os.getpid()))
    # We own the lock
except FileExistsError:
    # Lock held by another process
    pass

Why this works

Mode "x" provides atomic exclusive creation — either you create it or you don't; no race condition.

Code examples
Triggerpython
import os
os.mkdir("/tmp")  # FileExistsError: File exists
Handle with try/exceptpython
import os
try:
    os.mkdir(path)
except FileExistsError:
    pass  # directory already exists
Avoid with exist_ok=Truepython
import os
os.makedirs(path, exist_ok=True)  # never raises FileExistsError
Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors