python: why does os.makedirs cause WindowsError?

In python, I have made a function to make a directory if does not already exist.

def make_directory_if_not_exists(path):
    try:
        os.makedirs(path)
        break    
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

On Windows, sometimes I will get the following exception:

WindowsError: [Error 5] Access is denied: 'C:...my_path'

It seems to happen when the directory is open in the Windows File Browser, but I can't reliably reproduce it. So instead I just made the following workaround.

def make_directory_if_not_exists(path):
    while not os.path.isdir(path):
        try:
            os.makedirs(path)
            break    
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
        except WindowsError:
            print "got WindowsError"
            pass       

What's going on here, ie when does Windows mkdir give such an access error? Is there a better solution?


A little googling reveals that this error is raised in various different contexts, but most of them have to do with permissions errors. The script may need to be run as administrator, or there may be another program open using one of the directories that you are trying to use.


You should use OSError as well as IOError. See this answer, you'll use something like:

  def make_directory_if_not_exists(path):
    try:
        os.makedirs(path)
    except (IOError, OSError) as exception:
        if exception.errno != errno.EEXIST:
           ...

在你的问题上更好的解决方案,我会在这里使用简单明了的三行代码:

def make_directory_if_not_exists(path):
    if not os.path.isdir(path):
        os.makedirs(path)
链接地址: http://www.djcxy.com/p/14652.html

上一篇: OpenCV VideoCapture根本无法从我的网络摄像头读取

下一篇: python:为什么os.makedirs会导致WindowsError?