File or directory already exists
Production Risk
Use exist_ok=True for idempotent directory creation in deployment scripts.
A subclass of OSError (errno EEXIST) raised when trying to create a file or directory that already exists.
- 1os.mkdir() on a directory that already exists
- 2open() with mode "x" (exclusive creation) on an existing file
- 3os.link() creating a hard link that already exists
mkdir() on an existing directory.
import os
os.mkdir('/tmp') # /tmp already existsexpected output
FileExistsError: [Errno 17] File exists: '/tmp'
Fix 1
Use exist_ok=True with makedirs
WHEN Creating directories that may already exist
import os
os.makedirs('/path/to/dir', exist_ok=True) # No error if existsWhy 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
try:
with open('lockfile', 'x') as f:
f.write(str(os.getpid()))
# We own the lock
except FileExistsError:
# Lock held by another process
passWhy this works
Mode "x" provides atomic exclusive creation — either you create it or you don't; no race condition.
import os
os.mkdir("/tmp") # FileExistsError: File existsimport os
try:
os.mkdir(path)
except FileExistsError:
pass # directory already existsimport os os.makedirs(path, exist_ok=True) # never raises FileExistsError
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev