Grav
Grav

Reputation: 407

When using python os.rmdir, get PermissionError: [WinError 5] Access is denied

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!

Upvotes: 22

Views: 62092

Answers (6)

Jacob Thomas
Jacob Thomas

Reputation: 1

I had the same issue in shutil module, but got it resolved by removing the parent folder from windows quick access explore.

Upvotes: 0

sebvargo
sebvargo

Reputation: 673

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

Upvotes: 9

Osama Adly
Osama Adly

Reputation: 519

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

Upvotes: 13

Raymond Reddington
Raymond Reddington

Reputation: 1837

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

import shutil
shutil.rmtree('/path/to/your/dir/')

Upvotes: 23

Grav
Grav

Reputation: 407

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!

Upvotes: 10

Anil_M
Anil_M

Reputation: 11443

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

Upvotes: 2

Related Questions