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

15

36

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?

Eliseo answered 24/7, 2012 at 6:8 Comment(0)
P
48

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")
Potbellied answered 24/7, 2012 at 6:18 Comment(0)
L
44

try the inbuilt shutil module

shutil.rmtree(folder+"New Folder")

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

Limber answered 24/7, 2012 at 6:47 Comment(1)
You should use os.path.join() when adding paths :)Ziguard
W
22

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

os.chmod(filePath, 0o777)
os.remove(filePath)
Weisler answered 6/5, 2018 at 8:30 Comment(3)
Thanks. I think this is an actual answer to the question.Ostracon
This worked for me, but @Alexander I'm curious -- since we're about to delete the file anyway, is it still an issue?Alisiaalison
Since the file is gonna being deleted afterwards, settings the perms to 777 should be ok. Will delete my previous comment.Francoisefrancolin
M
14

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

Monomolecular answered 8/11, 2013 at 16:24 Comment(1)
os.rmdir() will remove an empty directory. shutil.rmtree() will delete a directory and all its contents.Disagree
Y
10

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))
Yiddish answered 24/7, 2012 at 6:54 Comment(0)
E
5

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

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

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

Edmondedmonda answered 30/1, 2021 at 23:55 Comment(0)
F
4

If you want remove folder, you can use

os.rmdir(path)
Factional answered 28/4, 2019 at 13:50 Comment(0)
R
1

If it's a directory, then just use:

os.rmdir("path")
Ratchet answered 18/9, 2019 at 9:33 Comment(0)
P
1
import os
import shutil


dir = os.listdir(folder)
for file in dir:
    if os.path.isdir(f'{folder}\\{file}'):
       shutil.rmtree(os.path.join(f'{folder}\\{file}'))
    else:
       os.remove(f'{folder}\\{file}')
Psalterium answered 11/4, 2023 at 16:55 Comment(3)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions applyRitch
folder= path of your file or folder, loop for to check all the items in the directory, and say if it is a file or folder, condition if to validate if it is a folder use shutil if it is a file use filePsalterium
@douglas carmaem ... Please add the additional explanation directly in your question, not in a comment. Your additional explanation is still unclear. Please take the time to use complete sentences, proper punctuation and capitalization. This answer could stay here for many years to come. Thank you.Landaulet
R
0

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)
Repentant answered 19/2, 2016 at 11:15 Comment(0)
H
0

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

Headon answered 18/9, 2018 at 5:56 Comment(0)
P
0

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")
Pedicel answered 23/6, 2021 at 13:44 Comment(1)
So your answer is testing if the file exists and if it doesn't then it doesn't try to remove it. However the OP was asking about the folder.Undeniable
P
0

In my case it was due to lack of admin privileges. I solved it running terminal or cmd as administrator

windows key -> cmd -> right click -> run as administrator

Piscatelli answered 16/10, 2022 at 15:8 Comment(0)
N
0

I has same issue on Server version OS. But that issue was not workstation type OS. I add next simple code (os.chmod) and an issue has been lost:

import os
import stat

os.chmod(file, stat.S_IWRITE)
os.remove(file)
Nerta answered 18/9, 2023 at 6:31 Comment(0)
Z
0

In case it helps - you could recursively delete files, and then directories, with try..except for each item, to ignore exceptions.

Realize this is not ideal, but in my case I tried many other things (using various delete functions, and a context manager to try to force release of file/directory locks) - but Python kept holding on to maybe 1 file out a huge set of files, preventing directory deletion.

Something like this will delete all files/directories that can be deleted, under 'temp_dir':

import os
import shutil

def _rmrf(temp_dir):
    os.chmod(temp_dir, 0o777) # add full permissions
    shutil.rmtree(temp_dir)

def _delete_files_recursively(temp_dir):
    for dirpath, _dirnames, filenames in os.walk(temp_dir):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                os.remove(fp)
            except:
                pass

def _delete_dirs_recursively(temp_dir):
    for dirpath, dirnames, _filenames in os.walk(temp_dir):
        for d in dirnames:
            dp = os.path.join(dirpath, d)
            try:
                _rmrf(dp)
            except:
                pass

def delete_dir_contents(temp_dir):
    _delete_files_recursively(temp_dir)
    _delete_dirs_recursively(temp_dir)

A more complete example is here:

https://github.com/mrseanryan/py_utils/blob/master/util_robust_delete.py

Zonnya answered 7/12, 2023 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.