Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: why does os.makedirs cause WindowsError?

Tags:

python

windows

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, i.e. when does Windows mkdir give such an access error? Is there a better solution?

like image 465
izak Avatar asked Jul 12 '13 16:07

izak


2 Answers

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:
           ...
like image 115
J. Peterson Avatar answered Sep 27 '22 17:09

J. Peterson


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.

like image 21
austin-schick Avatar answered Sep 27 '22 16:09

austin-schick