python filesystem_error ai_generated true

FileExistsError: [Errno 17] File exists

ID: python/fileexistserror

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

File or directory already exists. Common with os.makedirs() or shutil.copy().

generic

Workarounds

  1. 95% success Use exist_ok=True: os.makedirs(path, exist_ok=True)
    os.makedirs(path, exist_ok=True)

    Sources: https://docs.python.org/3/library/os.html#os.makedirs

  2. 95% success Use pathlib: Path(path).mkdir(parents=True, exist_ok=True)
    Path(path).mkdir(parents=True, exist_ok=True)

    Sources: https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir

Dead Ends

Common approaches that don't work:

  1. Delete the file/directory first 60% fail

    Race condition — another process may recreate it

  2. Use try/except to ignore the error globally 55% fail

    May hide other FileExistsError from different operations

Error Chain

Frequently confused with: