marsh
marsh

Reputation: 2720

Deleting Folders on drive

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?

Upvotes: 0

Views: 92

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148890

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)

Upvotes: 1

Related Questions