Home » Python “FileExists” error when making directory

Python “FileExists” error when making directory

To solve Python “FileExists” error when making directory error follow below methods.


  File "/usr/lib/python2.7/os.py", line 35, in makedirs
OSError: [Errno 17] File exists

How to solve Python “FileExists” error when making directory ?

Refer the given methods to solve the issue.

Method 1:

Description: Simply checking to see if the directory exists generates this error message [Errno 17]. File exists because we are only verifying if the directory name exists or not, which will return the directory name of the mydir value being supplied but not whether or not it already exists. What is missing is a check to see if that directory already exists, which can be done by inspecting the path with os.path.exists() and passing the directory name in there.

   if not os.path.exists(os.path.dirname(mydir)):
except OSError as err:

Method 2 :

You can use the exist_ok argument while creating a folder in order to avoid this error.

os.makedirs(mydir, exist_ok=True)

Hope the above solution works.

Also read : UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128)