Is there a foolproof way to give the system enough time to delete a folder before running copytree
Asked Answered
D

1

8

I have some directories that I need to update I was using the following code

for newdir in newdirs:
    olddir = newdir.replace('h:\\','G:\\').replace('_academic','')
    shutil.rmtree(newdir)
    shutil.copytree(olddir,newdir)

I would occasionally get an error

WindowsError: [Error 5] Access is denied: 'h:\\mydir\\sub1\\sub2\\sub3\\sub4\\sub5'

since the error would not happen on the previous directories I decided that the cause must be some access conflict - too little time was taking place between the rmtree call and copytree so I modified the code to waste some time

for newdir in newdirs:
    olddir = newdir.replace('h:\\','G:\\').replace('_academic','')
    shutil.rmtree(newdir)
    for item in range(0,20,1):
        pass
    shutil.copytree(olddir,newdir)

This made the error go away and the old directory was copied to the new location.

I don't like this because it seems pretty ramshackle - even for me.

  1. Am I wrong about the cause of the error (conflict)
  2. Is there a better way to make sure the system has enough time to complete the rmtree operation before we begin the copytree?
Decided answered 1/2, 2014 at 23:59 Comment(0)
F
10

If the error goes away when you wait, you're probably not wrong about the cause. So following up on the idea of waiting, but waiting with purpose, this might be ever so slightly better:

for newdir in newdirs:
    olddir = newdir.replace('h:\\','G:\\').replace('_academic','')
    shutil.rmtree(newdir)
    while os.path.exists(newdir): # check if it exists
        pass
    shutil.copytree(olddir,newdir)

Should some strange error occur preventing the directory from being removed but not raising an exception, the while loop could theoretically go forever, but I find that highly unlikely.

I'm not proud of this solution at all, but barring new knowledge, this should be a little more fool-proof than an arbitrary delay.

Flaxman answered 2/2, 2014 at 0:4 Comment(1)
I like this because you are exactly right, waiting with a purpose instead of some random count. Thanks for the suggestion.Decided

© 2022 - 2024 — McMap. All rights reserved.