Cannot delete folder with os.remove (WindowsError: [Error 5] Access denied: 'c: / temp / New Folder')

I am working on a test case for which I am creating some subdirectories. However, I do not seem to have permission to delete them. My UA is an administrator account (Windows XP).

First I 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 the "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 anyone know what is going wrong?

+9
source share
9 answers

os.remove requires a file path and an OSError occurs if the path is a directory .

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

What will happen:

Delete (delete) the path to the directory. It works only when the directory is empty, otherwise OSError will be raised.

Creating paths is also safer with os.path.join :

 os.path.join("c:\\", "temp", "new folder") 
+17
source

try the built-in shutter module

 shutil.rmtree(folder+"New Folder") 

this recursively deletes the directory, even if it has content.

+16
source

os.remove() only works with files. This does not work on directories. According to the documentation :

os.remove (path) Delete (delete) the path to the file. If the path is a directory, an OSError is raised; see rmdir () below to remove the directory. This is identical to the unlink () function described below. On Windows, an attempt to delete the file in use raises an exception; on Unix, the directory entry is deleted, but the storage allocated for the file becomes inaccessible until the original file is no longer used.

use os.removedirs() for directories

+9
source

U can use the Shutil module to delete the directory and its subfolders

 import os import shutil for dir in os.listdir(folder): shutil.rmtree(os.path.join(folder,dir)) 
+7
source

For Python 3.6, the file access mode should be 0o777:

 os.chmod(filePath, 0o777) os.remove(filePath) 
+3
source

The file is in read-only mode, so change the file resolution using the os.chmod() function, and then try using os.remove() .

Example:

Change the Permission file to 0777 , and then delete the file.

 os.chmod(filePath, 0777) os.remove(filePath) 
0
source

The reason you cannot delete folders is because to delete a subfolder on drive C: you need administrator rights. Call admin rights in python or do the following hack

Create a simple .bat file with the following shell command

 del /q "C:\Temp\*" FOR /D %%p IN ("C:\temp\*.*") DO rmdir "%%p" /s /q 

Save it as file.bat and call this bat file from your python file

The bat file will handle the removal of subfolders from drive C:

0
source

If you want to delete the folder, you can use

 os.rmdir(path) 
0
source

If this is a directory, then simply use:

 os.rmdir("path") 
0
source

All Articles