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()
oros.makedirs()
- Trying to create a directory that already exists using the
.mkdir()
method on apathlib.Path
object - Trying to create a file that already exists using the
.touch()
method on apathlib.Path
object, when theexist_ok
parameter is set toFalse
FileExistsError
Examples
An example of when the exception appears:
>>> 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:
>>> 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:
>>> 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()
:
>>> 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
.
Related Resources
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.
For additional information on related topics, take a look at the following resources: