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

Viewed 87710

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?

11 Answers

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

os.chmod(filePath, 0o777)
os.remove(filePath)

os.remove() only works on files. It doesn't work on directories. According to the documentation:

os.remove(path) Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

use os.removedirs() for directories

If you want remove folder, you can use

os.rmdir(path)

Use os.rmdir instead of os.remove to remove a folder

os.rmdir("d:\\test")

It will remove the test folder from d:\\ directory

If it's a directory, then just use:

os.rmdir("path")

The reason you can't delete folders because to delete subfolder in C: drive ,you need admin privileges Either invoke admin privileges in python or do the following hack

Make a simple .bat file with 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

Bat file will handle deleting subfolders from C: drive

Can't remove a folder with os.remove

import os

if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")
Related