17

I'm building a file-transfer script, and the source cleanup function makes use of os.rmdir('C:\\Users\\Grav\\Desktop\\TestDir0\\Om'). This is the error I get:

PermissionError: [WinError 5] Access is denied: 'C:\\Users\\Grav\\Desktop\\TestDir0\\Om'

I checked the permissions on the folder Om through the Windows 7 and they are set to allow deletion for my user account. I've also tried setting my interpreter to run as admin. The problem persists and I'm stymied. Much obliged to anyone with insight!

Grav
  • 347
  • 1
  • 2
  • 15
  • 7
    Did you close your file in your code before trying to remove it? – idjaw Apr 01 '16 at 15:29
  • 4
    In Windows you can't* access or delete a file that's being held open by some other process. Some call it a feature. *at least without doing some weird mangling with the win32 api – Wayne Werner Apr 01 '16 at 15:37
  • I didn't actually _open_ the file (also, it's a folder so I'm not sure if Python treats it as "open" or "closed" like a file object), but I did copy the tree that contained it using shutil.copytree. Perhaps the copy function leaves folder objects in an "open" state? – Grav Apr 01 '16 at 15:41

5 Answers5

15

I had a same issue, could do it via shutil module.

import shutil
shutil.rmtree('/path/to/your/dir/')
Raymond Reddington
  • 1,709
  • 1
  • 13
  • 21
13

uncheck read-only attribute box found in the properties of the file/folder. enter image description here

Osama Adly
  • 519
  • 5
  • 4
9

I found a solution here: What user do python scripts run as in windows?

It seems as if the offending folder has a stubborn read-only attribute. Adding in a handler to change such read-only flags worked like a charm for me.

All of you who posted suggestions, you helped me track down the final answer, so thank you!

Community
  • 1
  • 1
Grav
  • 347
  • 1
  • 2
  • 15
8

Try deleting all files in the directory before deleting the directory:

import os
path_to_dir  = 'C:\\Users\\Desktop\\temp'  # path to directory you wish to remove
files_in_dir = os.listdir(path_to_dir)     # get list of files in the directory

for file in files_in_dir:                  # loop to delete each file in folder
    os.remove(f'{path_to_dir}/{file}')     # delete file

os.rmdir(path_to_dir)                      # delete folder
sebvargo
  • 613
  • 7
  • 10
2

Can you check if:

  1. You are not in dir 0m and running script from there.
  2. You don't have any windows open that list the 0m dir.
  3. Since 0m is a subdirectory of TestDir0, you have correct permissions for TestDir0
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Anil_M
  • 10,893
  • 6
  • 47
  • 74
  • Certainly. I'm not running from `Om`, I don't have any windows open except the interpreter and the .py file itself in Notepad++, and I have permissions for `TestDir0`. – Grav Apr 01 '16 at 17:31