FileExistsError

FileExistsError is a built-in exception that is raised when an operation attempts to create a file or directory that already exists. This exception is part of the OSError family, which covers a variety of system-related errors.

If you’re working with file or directory creation, you might encounter this exception when you try to create a file or directory without first checking if it already exists. This helps to avoid unintentionally overwriting existing files or directories.

FileExistsError Occurs When

  • Trying to create a file using the open() function with mode "x", which stands for exclusive creation
  • Trying to create a directory that already exists using os.mkdir() or os.makedirs()
  • Trying to create a directory that already exists using the .mkdir() method on a pathlib.Path object
  • Trying to create a file that already exists using the .touch() method on a pathlib.Path object, when the exist_ok parameter is set to False

FileExistsError Examples

An example of when the exception appears:

Python
>>> from pathlib import Path
>>> directory = Path("project")
>>> directory.mkdir()
>>> directory.mkdir()  # Try to create the directory twice
Traceback (most recent call last):
    ...
FileExistsError: [Errno 17] File exists: 'directory'

An example of how to handle the exception:

Python
>>> from pathlib import Path
>>> directory = Path("project")
>>> try:
...     directory.mkdir()
... except FileExistsError:
...     print("The directory already exists")
...
The directory already exists

FileExistsError How to Fix It

To fix a FileExistsError, you can check whether a file or directory exists before attempting to create it. Here’s an example:

Python
>>> import os
>>> directory = "project"
>>> os.mkdir(directory)
>>> if not os.path.exists(directory):
...     os.mkdir(directory)
...

Because the directory already exists, the check fails and the indented code doesn’t run.

If you’re using pathlib, then you can avoid raising the exception by setting exist_ok to True when creating directories with .mkdir():

Python
>>> from pathlib import Path
>>> directory = Path("project")
>>> directory.mkdir(exist_ok=True)
>>> directory.mkdir(exist_ok=True)  # Try to create the directory twice

If the project/ directory doesn’t exist, then Python creates it. If project/ already exists, then nothing happens.

When creating files with .touch(), exist_ok defaults to True.

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Martin Breuss