close

[Solved] Python “FileExists” error when making directory

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python “FileExists” error when making directory in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python “FileExists” error when making directory Error Occurs?

Today I get the following error Python “FileExists” error when making directory in python.

How To Solve Python “FileExists” error when making directory Error ?

  1. How To Solve Python “FileExists” error when making directory Error ?

    To Solve Python “FileExists” error when making directory Error As of Python >=3.2os.makedirs() can take a third optional argument exist_ok:
    os.makedirs(mydir, exist_ok=True)

  2. Python “FileExists” error when making directory

    To Solve Python “FileExists” error when making directory Error As of Python >=3.2os.makedirs() can take a third optional argument exist_ok:
    os.makedirs(mydir, exist_ok=True)

Solution 1

Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception

while True:
    mydir = next_dir_name()
    try:
        os.makedirs(mydir)
        break
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise   
        # time.sleep might help here
        pass

If you have a lot of threads trying to make a predictable series of directories this will still raise a lot of exceptions, but you will get there in the end. Better to just have one thread creating the dirs in that case

Solution 2

As of Python >=3.2os.makedirs() can take a third optional argument exist_ok:

os.makedirs(mydir, exist_ok=True)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read