How to Resolve Python "FileExistsError: [Errno 17] File exists"
When working with the file system in Python, creating directories is a common operation using the os
module. However, if you attempt to create a directory that already exists using certain functions, Python will raise a FileExistsError: [Errno 17] File exists
.
This guide explains why this error occurs and presents the standard Pythonic ways to handle or prevent it, primarily using os.makedirs()
.
Understanding the Error: Creating Existing Directories
The FileExistsError
is a specific type of OSError
indicating that a file system operation (like creating a directory or file) failed because the target path already exists in a way that conflicts with the operation. For directory creation, it means you tried to make a directory with a name that is already taken by either a directory or a file at that location.
Cause: Using os.makedirs()
(or os.mkdir()
) on an Existing Path
The most common scenario for this error is calling os.makedirs(directory_path)
or os.mkdir(directory_path)
when directory_path
already exists. By default, these functions expect the target path not to exist.
import os
dir_name = 'my_existing_directory'
# --- Step 1: Ensure the directory exists for the demo ---
if not os.path.exists(dir_name):
print(f"Creating directory '{dir_name}' for demo.")
os.makedirs(dir_name) # Create it initially
else:
print(f"Directory '{dir_name}' already exists for demo.")
# --- Step 2: Attempt to create it AGAIN with default behavior ---
print(f"\nAttempting to create '{dir_name}' again...")
try:
# ⛔️ FileExistsError: [Errno 17] File exists: 'my_existing_directory'
# This line will raise the error because the directory exists
# and exist_ok defaults to False.
os.makedirs(dir_name)
print("Second creation attempt succeeded (unexpected!).")
except FileExistsError as e:
print(f"Caught expected error: {e}")
except Exception as e:
print(f"Caught unexpected error: {e}")
Solution 1: Using os.makedirs(exist_ok=True)
(Recommended)
The most Pythonic and often preferred way to handle this when using os.makedirs()
is to use the exist_ok
parameter, introduced in Python 3.2. Setting exist_ok=True
tells makedirs
not to raise an error if the directory already exists. It will still create any necessary parent directories if they don't exist.
import os
dir_name = 'my_persistent_directory'
nested_dir = os.path.join(dir_name, 'subdir1', 'subdir2')
# ✅ Use exist_ok=True
# This will create 'my_persistent_directory', 'subdir1', and 'subdir2' if they don't exist.
# If they *do* already exist, it will do nothing and NOT raise an error.
os.makedirs(nested_dir, exist_ok=True)
print(f"Successfully ensured directory exists (or created it): '{nested_dir}'")
# Running it again causes no error:
os.makedirs(nested_dir, exist_ok=True)
print("Running makedirs with exist_ok=True again causes no error.")
Important: This exist_ok
parameter is available for os.makedirs()
but not for the simpler os.mkdir()
function (which only creates a single directory, not intermediate ones). For robust directory creation, os.makedirs(exist_ok=True)
is usually the best choice.
Solution 2: Using a try...except FileExistsError
Block
If you are using an older Python version (before 3.2) or need to specifically know if the directory was created versus already existed, or if using os.mkdir()
, you can wrap the creation call in a try...except
block.
import os
dir_name = 'another_directory'
try:
print(f"Attempting to create '{dir_name}' using try/except...")
os.makedirs(dir_name) # Or os.mkdir(dir_name)
print(f"Directory '{dir_name}' created successfully.")
except FileExistsError:
# ✅ Handle the specific error if the directory already exists
print(f"Directory '{dir_name}' already exists, no action needed.")
except OSError as e:
# Handle other potential OS errors (e.g., permission denied)
print(f"An OSError occurred: {e}")
# Running it again will now hit the except block
try:
os.makedirs(dir_name)
print(f"Directory '{dir_name}' created successfully (second try).")
except FileExistsError:
print(f"Directory '{dir_name}' already exists (second try).") # This will run
except OSError as e:
print(f"An OSError occurred (second try): {e}")
You can use pass
inside the except FileExistsError:
block if you simply want to ignore the error and continue.
Solution 3: Checking Existence with os.path.exists()
Before Creation
Another approach is to explicitly check if the directory exists before attempting to create it using os.path.exists()
.
import os
dir_name = 'pre_checked_directory'
print(f"Checking if '{dir_name}' exists before creating...")
# ✅ Check first
if not os.path.exists(dir_name):
print(f"Directory '{dir_name}' does not exist. Creating...")
try:
os.makedirs(dir_name) # Create it only if it doesn't exist
print(f"Directory '{dir_name}' created.")
except OSError as e:
print(f"Error creating directory: {e}")
else:
print(f"Directory '{dir_name}' already exists.")
# Running again will just hit the else block
if not os.path.exists(dir_name):
print(f"Directory '{dir_name}' does not exist. Creating...")
# ... creation code ...
else:
print(f"Directory '{dir_name}' already exists (second check).") # This is executed
Caution (Race Condition): While simple, this method has a small theoretical risk of a "race condition" in multi-threaded or multi-process environments. Another process could potentially create the directory between your os.path.exists()
check and your os.makedirs()
call, causing the makedirs
call to fail unexpectedly. The exist_ok=True
and try...except
methods are generally safer in concurrent scenarios.
os.makedirs()
vs. os.mkdir()
os.mkdir(path)
: Creates a single directory atpath
. It fails if the directory already exists or if any intermediate parent directories do not exist. It does not have anexist_ok
parameter.os.makedirs(path, exist_ok=False)
: Creates the directory atpath
, including creating any necessary intermediate parent directories. Withexist_ok=False
(the default), it fails if the final directory already exists. Withexist_ok=True
, it succeeds even if the directory exists.
For most common use cases where you want to ensure a directory path exists, os.makedirs(path, exist_ok=True)
is the most convenient and robust option.
Conclusion
The FileExistsError: [Errno 17] File exists
in Python signals an attempt to create a directory that already exists.
- The recommended way to handle this when you want to ensure a directory structure exists is to use
os.makedirs(directory_path, exist_ok=True)
. - This creates the directory (and any parents) if needed but gracefully does nothing if it already exists.
- Alternatively, especially for older Python versions or
os.mkdir()
, use atry...except FileExistsError
block to catch and handle the specific error. - Explicitly checking with
os.path.exists()
first is also possible but less robust against race conditions.