4

I'm writing a code in Python, in which I check if a certain folder exists; if it does, I remove it and create a new one (with the same name). The code is as follows:

 if os.path.exists(output_folder):
     shutil.rmtree(output_folder)  
 os.makedirs(output_folder)

This code works fine, accept for when I have that specific output_folder open with the windows explorer. When it's open, I get the following error in my code:

WindowsError: [Error 5] Access is denied: [foldername]

Simultaneously, windows explorer switches itself to foldername's parent directory, and throws an error.

Is there a way to make python ignore the error and continue running, or am I asking for something that is impossible due to the system?

I tried using shutil.rmtree(output_folder, ignore_errors=True) but it didn't change anything.

Cheshie
  • 2,777
  • 6
  • 32
  • 51

1 Answers1

5

You can use Python's exception handling to catch the error. You would also probably benefit from a short delay before creating the folder again to give Windows Explorer a chance to close:

import shutil
import time


try:    
    shutil.rmtree(output_folder)  
except WindowsError as e:
    print("Failed to delete")       # Or just pass

time.sleep(0.5)
os.makedirs(output_folder)
Martin Evans
  • 45,791
  • 17
  • 81
  • 97