Python “FileExists” error when making directory

空扰寡人 提交于 2019-11-28 18:37:12

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 != os.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

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

os.makedirs(mydir, exist_ok=True)

Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the isdir and makedirs calls.

However, it could also be possible that a file with the same name exists - in that case os.path.exists would return True but os.path.isdir returns false.

I had a similar issues and here is what I did

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

Description: Just checking if the directory already exist throws this error message [Errno 17] File exists because we are just checking if the directory name exist or not which will return the directory name of the mydir value being passed but not if it already exist or not. What is being missed is not checking if that directory already exist which can be done by checking the path with os.path.exists() and in there we passed the respective directory name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!