'shutil.rmtree() raises exception WindowsError: Access is denied:
Trying to automatically delete files with a python script and i get:
Traceback (most recent call last):
Python script "5", line 8, in <module>
shutil.rmtree(os.path.join(root, d))
File "shutil.pyc", line 221, in rmtree
File "shutil.pyc", line 219, in rmtree
WindowsError: [Error 5] Access is denied: 'C:\\zDump\\TVzip\\Elem.avi'
using this
import os
import shutil
for root, dirs, files in os.walk(eg.globals.tvzip):
for f in files:
os.remove(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk(eg.globals.tvproc):
for f in files:
os.remove(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
All is being run as administrator, any help?
Solution 1:[1]
While I can't comment on the Windows permissions (or lack there of), assuming you have correct perms, then an open file handle is really likely.
I just wanted to mention, shutil.rmtree will clear out any files in the directory it removes... so you can chop your algorithm in half, and stop removing files one by one.
Solution 2:[2]
Typically, this error comes up on Windows when the path you are trying to remove is read-only. You could try something along the lines of the below which may work:
import stat
import os
def make_dir_writable(function, path, exception):
"""The path on Windows cannot be gracefully removed due to being read-only,
so we make the directory writable on a failure and retry the original function.
"""
os.chmod(path, stat.S_IWRITE)
function(path)
if os.path.exists(path):
shutil.rmtree(path, onerror=make_dir_writable)
Documentation on the subject can be found here: https://docs.python.org/3.9/library/shutil.html#shutil.rmtree
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael W. |
| Solution 2 | Justin Hammond |
