Skip to content

How to Resolve Python "FileExistsError: [Errno 17] File exists"

How to handle Python's FileExistsError when using os.makedirs() or os.mkdir(), including the recommended exist_ok=True parameter and alternative error-handling approaches.

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'

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

print(f"\nAttempting to create '{dir_name}' again...")
try:
    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}")

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

os.makedirs(nested_dir, exist_ok=True)

print(f"Successfully ensured directory exists (or created it): '{nested_dir}'")

os.makedirs(nested_dir, exist_ok=True)
print("Running makedirs with exist_ok=True again causes no error.")

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:
    print(f"Directory '{dir_name}' already exists, no action needed.")
except OSError as e:
    print(f"An OSError occurred: {e}")

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

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

if not os.path.exists(dir_name):
     print(f"Directory '{dir_name}' does not exist. Creating...")
else:
     print(f"Directory '{dir_name}' already exists (second check).") # This is executed

os.makedirs() vs. os.mkdir()

  • os.mkdir(path): Creates a single directory at path. It fails if the directory already exists or if any intermediate parent directories do not exist. It does not have an exist_ok parameter.
  • os.makedirs(path, exist_ok=False): Creates the directory at path, including creating any necessary intermediate parent directories. With exist_ok=False (the default), it fails if the final directory already exists. With exist_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 a try...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.
Navigation