Python: why os.makedirs raise a WindowsError?

In python, I created a function to make a directory if it 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, the following exception sometimes occurs:

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

It seems that when the directory is open in Windows File Browser, but I can not reliably play it. So instead, I 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 happens here, i.e. when does windows mkdir give such an access error? Is there a better solution?

+7
python windows
source share
3 answers

A little googling shows that this error occurs in different contexts, but most of them are related to permission errors. It is possible that the script must be running as an administrator, or it may be that another program is open using one of the directories you are trying to use.

+1
source share

You must use OSError as well as IOError. See this answer, you will use something like:

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

in your question about the best solution, I would use a simple and clear three-line code:

 def make_directory_if_not_exists(path): if not os.path.isdir(path): os.makedirs(path) 
-one
source share

All Articles