Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove a folder with os.remove (WindowsError: [Error 5] Access is denied: 'c:/temp/New Folder')

I'm working on a test case for which I create some subdirs. However, I don't seem to have the permission to remove them anymore. My UA is an Administrator account (Windows XP).

I first tried:

folder="c:/temp/"  for dir in os.listdir(folder):      os.remove(folder+dir) 

and then

folder="c:/temp/"  os.remove(folder+"New Folder") 

because I'm sure "New Folder" is empty. However, in all cases I get:

Traceback (most recent call last):    File "<string>", line 3, in <module>  WindowsError: [Error 5] Access is denied: 'c:/temp/New Folder' 

Does anybody know what's going wrong?

like image 566
Sergio Da Silva Avatar asked Jul 24 '12 06:07

Sergio Da Silva


People also ask

How do you delete a folder whose access is denied?

To work around this issue, use either of the following methods: When you delete the files or folders by using Windows Explorer, use the SHIFT+DELETE key combination. This bypasses the Recycle Bin. Open a command prompt window and then use the rd /s /q command to delete the files or folders.

How do you force delete a folder using CMD Access Denied?

Syntax : Type RMDIR /S /Q “” (where is the Location of folder you wish to delete).

How do I fix access denied in Python?

PermissionError: [errno 13] Permission denied occurs when someone tries to access a file from Python without having the necessary permissions. To fix this error, use the full chmod or chown command to change the permissions on the file to allow the correct user and/or squad to access the file.

How do you delete a non empty directory in Python?

Shutil rmtree() to Delete Non-Empty Directory The rmtree('path') deletes an entire directory tree (including subdirectories under it). The path must point to a directory (but not a symbolic link to a directory). Set ignore_errors to True if you want to ignore the errors resulting from failed removal.


2 Answers

os.remove requires a file path, and raises OSError if path is a directory.

Try os.rmdir(folder+'New Folder')

Which will:

Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.

Making paths is also safer using os.path.join:

os.path.join("c:\\", "temp", "new folder") 
like image 102
Aesthete Avatar answered Oct 15 '22 10:10

Aesthete


try the inbuilt shutil module

shutil.rmtree(folder+"New Folder") 

this recursively deletes a directory, even if it has contents.

like image 42
appusajeev Avatar answered Oct 15 '22 09:10

appusajeev