views:

36

answers:

2

So here's my problem. I have a python script that takes a zipfile and extracts its contents. Then based on some constraint, I will try to delete the folder whose contents were just extracted. For some reason I get an error, WindowsError: [Error 5] Access is denied: 'Foldername' when i try to delete that folder. The simple code looks like the following

wzip = zipfile.ZipFile('zipfile.zip')

wzip.extractall()

wzip.close()

os.remove('ExtractedFolder')

If I run this in the interpreter I get the following:

Traceback (most recent call last): File "", line 1, in WindowsError: [Error 5] Access is denied: 'ExtractedFolder'

I'm using Python 2.6 on Windows Vista 32-bit and I'm kinda baffled as to why this might be happening.

+2  A: 

Many reasons possible.

  1. You need to use os.rmdir to remove directories
  2. You need to empty the folder first - remember, the Windows command rmdir needs a /S option to remove the contents, and Python probably uses that.
  3. Is the unzip also using the archive's attributes? Read-only attributes may be applied.
  4. Are you reading anything from that folder, before you delete? You may not have closed it.
  5. Windows can cause similar problems with filenames containing unusual characters
Sanjay Manohar
I believe you're right on 1. and 2. os.remove was the wrong command and os.rmdir would have worked as well except for the fact that the folder is not empty.
A: 

I see a possible problem on Windows, which is that you could have an opened file in this directory. Make sure that you close explicitly all the files that you have opened using file.close() (your sample code looks right, though).

Also, it might be useful to have a look at shutils.rmtree: it can recursively remove directories, and capture errors.

Gael Varoquaux
Thanks. since the folder wasn't empty, I was supposed to use shutil.rmtree