0

I am trying to delete a collection of folders on my drive. These directories are not empty. I have come up with a solution as follows:

import shutil
import os

path = "main/"
folderList = ['Blah', 'Blah', 'Blah'];

print ("Cleaning Project at %s" % path)

for c in folderList:
    strippedPath = (path + c).strip("\n")
    print ("Cleaning path " + strippedPath)
    if os.path.exists(strippedPath):
        try:
            shutil.rmtree(strippedPath)
        except OSError as why:
            pass

print ("Done Cleaning Project")

The problem is that without the try / catch I get a error that says

PermissionError: [WinError 5] Access is denied: 'PathToFileHere'

Pressing the delete key on windows will work fine. Can someone provide me a command that will remove this directory without errors?

marsh
  • 2,592
  • 5
  • 29
  • 53
  • I'm really stating the obvious here, but it's because Python doesn't have permission from your OS to complete that operation. This isn't something that you can fix from within your code; though there's probably a workaround with something like `subprocess`. – anon582847382 Oct 29 '14 at 17:54
  • What makes that particular folder so special? It removes the rest? – marsh Oct 29 '14 at 17:55
  • 1
    possible duplicate of [Python: shutil.rmtree fails on Windows with 'Access is denied'](http://stackoverflow.com/questions/2656322/python-shutil-rmtree-fails-on-windows-with-access-is-denied) – Alderven Oct 29 '14 at 18:29

1 Answers1

1

First you should avoid to silently swallow an Exception, but at least print or log it. But many thing can happen to a file, they may have Hidden, System or ReadOnly attributes. The current user may not have permissions on files but only on the containing folder. As Python is multi-platform its high-level commands can be less optimized for a particular OS (Windows in your case) than native ones.

You should first try to confirm that in a cmd window, the command rd /s folder correctly remove the folder that shutil.rmtree fails to delete, and if yes ask python so execute it vie the subprocess module :

subprocess.call("rd /s/q " + strippedPath)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252