Python Forum
os.remove() Access is denied - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: os.remove() Access is denied (/thread-29340.html)



os.remove() Access is denied - pythonnewbie138 - Aug-28-2020

I'm receiving the below error when attempting to use os.remove() if a directory is found to exist. I've seen suggestions of running the script in an admin command prompt, that did not help. Relevant code snippet is also below.
Any help with understanding why this is happening is much appreciated!

Error:
Traceback (most recent call last): File "C:\Users\REMOVED\Python Apps\My Progs\test5.py", line 38, in <module> os.remove(final_dest) PermissionError: [WinError 5] Access is denied: 'C:\\Users\\REMOVED\\Python Apps\\My Progs\\test_folder\\test_folder'
final_dest = os.path.join(dest, basename)
if os.path.exists(final_dest):
    os.remove(final_dest)
    os.mkdir(final_dest)
else:
    os.mkdir(final_dest)



RE: os.remove() Access is denied - bowlofred - Aug-28-2020

If you have a file, you can remove just that file with os.remove() or os.unlink(). Similar to /bin/rm, this function fails on directories.

If you have a (empty) directory, you can remove it with os.rmdir(). Similar to /bin/rmdir.

If you have a path and want it and everything underneath it removed if possible, you can do so with shutil.rmtree(). Similar to /bin/rm -r.

Also, older documentation stated that os.remove() would throw an OSError if it were handed a directory. Newer documentation states flatly that it now throws a IsADirectoryError. But it looks like that may be OS dependent. I do see the newer error on Linux, but I don't on MacOS (which still throws OSError, even on 3.8). I'm guessing that Windows does the same, but I can't test that immediately.

Linux/Python 3.7.4
>>> os.remove("dir")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IsADirectoryError: [Errno 21] Is a directory: 'dir'
MacOS/Python 3.8.2
>>> os.remove("dir")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 1] Operation not permitted: 'dir'



RE: os.remove() Access is denied - pythonnewbie138 - Aug-28-2020

Thank you for the explanation. shutil.rmtree() works great.

So the os module isn't capable to deleting a directory with contents?


RE: os.remove() Access is denied - bowlofred - Aug-28-2020

Most (all?) things in "os" are access to the operating system functions rather than implemented in python. So yes, you're correct. unlink() is the OS call to remove a file and it often fails when handed a directory. Python isn't really doing anything here other than handing the structure over to the OS and handing back any success/failure information.