3

I've reduced my issue to this:

import os, shutil

shutil.rmtree("wtf", True)
os.makedirs("wtf")

Now, when I run this I sometimes get the following error:

Traceback (most recent call last):
  File "wtf.py", line 4, in <module>
    os.makedirs("wtf")
  File "C:\Program Files (x86)\Python34\lib\os.py", line 244, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: 'wtf'

What could be causing this?

orlp
  • 112,504
  • 36
  • 218
  • 315
  • Does the error still occur if it's not immediately after, such as if the directory never existed in the first place? – mhlester May 29 '14 at 16:30
  • Try `shutil.rmtree("wtf")`. You will see that the directory is not deleted because the directory is not deletable by you. (If you give `True` for the second argument, the error is ignored) – falsetru May 29 '14 at 16:31
  • @falsetru Nope. In fact, putting `assert(os.path.isdir("wtf") == False)` in between the two lines __never__ fails. – orlp May 29 '14 at 16:52
  • @mhlester Could you rephrase that, I'm unsure what you mean. – orlp May 29 '14 at 16:52
  • I mean to ask if the error only occurs if you re-create it *immediately* after, like it's some sort of race condition, or if the error occurs making any directory in that location – mhlester May 29 '14 at 16:56
  • @mhlester Only when re-creating, creating an other directory never seems to fail. – orlp May 29 '14 at 16:58
  • One thing I've noticed is that the error only occurs, exactly half the time, when I have __an explorer window open in that location__. – orlp May 29 '14 at 16:58
  • As described in the [MSDN documentation for RemoveDirectory](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365488(v=vs.85).aspx) the RemoveDirectory call may return before the removal actually completes. Some of the details are unclear, e.g., it only seems to happen if Windows knows, somehow, that the call *will* succeed in the relatively near future, and your assert() suggests that Windows is even lying to the application that removed the directory, which certainly isn't documented! (It's also unclear just when Windows started doing this; I'm sure it didn't used to.) – Harry Johnston May 31 '14 at 11:32
  • Actually it seems it isn't new behaviour: see http://stackoverflow.com/questions/12798597/strange-exception-with-file-access-and-explorator-windows – Harry Johnston May 31 '14 at 12:03
  • Possible duplicate of [Permission denied doing os.mkdir(d) after running shutil.rmtree(d) in Python](https://stackoverflow.com/questions/16373747/permission-denied-doing-os-mkdird-after-running-shutil-rmtreed-in-python) – OmerB Oct 30 '17 at 13:17

0 Answers0