Solve - FileExistsError: [Errno 17] File exists in Python

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Check out my new book

Solve - FileExistsError: [Errno 17] File exists in Python #

The Python "FileExistsError: [Errno 17] File exists" occurs when we try to create a directory that already exists. To solve the error, set the exist_ok keyword argument to True in the call to the os.makedirs() method, e.g. os.makedirs(dir_name, exist_ok=True).

fileexistserror errno 17 file exists

Here is an example of how the error occurs.

main.py
import os dir_name = 'my_dir' # ⛔️ FileExistsError: [Errno 17] File exists: 'my_dir' os.makedirs(dir_name)

The my_dir directory already exists, so a FileExistsError is raised.

One way to get around this is to set the exist_ok keyword argument to True.

main.py
import os dir_name = 'my_dir' os.makedirs(dir_name, exist_ok=True)
Make sure you're using the os.makedirs() method, and not os.makedir() as the latter doesn't take a exist_ok keyword argument.

If exist_ok is set to True, you won't get a FileExistsError if the target directory already exists.

The value for the exist_ok parameter is set to False by default.

Alternatively, you can use a try/except block to handle the FileExistsError.

main.py
import os dir_name = 'my_dir' try: os.makedirs(dir_name) except FileExistsError: print('directory already exists')

We try to create the directory in the try block and if a FileExistsError is raised, the except block is ran.

You can use the pass statement if you don't want to handle the error in any way.

main.py
import os dir_name = 'my_dir' try: os.makedirs(dir_name) except FileExistsError: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

The os.makedirs method is used for recursive directory creation.

It makes all the intermediate-level directories needed to contain the nested directory.

Use the search field on my Home Page to filter through my more than 3,000 articles.