doberkofler
doberkofler

Reputation: 10341

Error when creating directory with os.makedirs immediately after removing it with shutil.rmtree

When trying to create a new (deep) directory (on a local ssd) immediately after removing it, Python 3.6 reports a PermissionError in the os.makedirs(dirName) line. The only way to work around this problem is to sleep for 1 second after removing the directory and then there is no error. Am I using the API the wrong way, is this a Python problem or what else could it be?

Example:

dirName = "a/b/c"

if os.path.isdir(dirName):
        shutil.rmtree(dirName)
        #time.sleep(1)

os.makedirs(dirName)

Error:

  File "C:\Program Files\Python37\lib\os.py", line 221, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: '...'

  File "C:\Program Files\Python37\lib\os.py", line 221, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: '...'

Upvotes: 1

Views: 989

Answers (1)

wovano
wovano

Reputation: 5073

Your code seems fine, however, there could be a few reasons why you get this error:

  1. On network drives, file operations have to be synchronized over the network and unfortunately that might sometimes cause this type of problems. A minor delay (and/or some other retry mechanism) is a nasty work-around that might solve the problem in such cases.

  2. If the directory is in use it cannot be deleted until the resource is freed by the corresponding application. The directory can be in use if you have any file in that directory opened in an editor. Some applications lock the directory even if you have closed the file (so you should close the application to release the directory). Also note that some background tasks (for example, Tortoise SVN, a backup utility or a virus scanner) may temporarily lock a directory.

    Note that this behavior may differ between Windows and Linux. In Linux, if a file is removed while still in use, the low-level file handle will remain valid until released by the corresponding application, but the file itself will be renamed to some temporary unique long file name, so you won't have this problem. Windows seems to handle it differently.

Upvotes: 1

Related Questions