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

扶醉桌前 提交于 2019-11-29 06:55:36

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")

try the inbuilt shutil module

shutil.rmtree(folder+"New Folder")

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

8bitwide

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

U can use Shutil module to delete the dir and its sub folders

import os
import shutil

for dir in os.listdir(folder):
    shutil.rmtree(os.path.join(folder,dir))
Thomas O. Tettey

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

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

File is in read only mode so change the file permission by os.chmod() function and then try with os.remove().

Ex:

Change the file Permission to 0777 and then remove the file.

os.chmod(filePath, 0777)
os.remove(filePath)
Sushen Sharma

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

a w

If you want remove folder, you can use

os.rmdir(path)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!