Python 3.3+Exceptionsexception
FileExistsError
built-in exceptions
Trying to create a file or directory that already exists (a subclass of OSError).
Syntax
raise FileExistsError
You get this from os.mkdir(), Path.mkdir(), or open() in 'x' mode — places where you demand that the target be brand new. The instinct to guard with os.path.exists() first is fragile: the file can appear between the check and the call, so either catch the exception or pass exist_ok=True to mkdir()/makedirs().
Examples
try:
raise FileExistsError
except FileExistsError as e:
print(type(e).__name__) # → FileExistsError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy