Everytime I try to delete a file using os.remove()
in Python 3.5.1, I get this message PermissionError: [WinError 5] Access is denied
And here is that simple code:
def clean_thrash(path):
dirlist=get_dirlist(path)
for f in dirlist:
fullname=os.path.join(path,f)
if fullname == os.path.join(path,"thrash.txt"):
os.remove(path)
if os.path.isdir(fullname):
clean_thrash(fullname)
Didn't even delete a single file in the directory or sub-directory.
I too had this problem, and after searching found a good solution.
Essentially, before calling os.remove(file_name)
we need change file permissions.
import stat
os.remove
, call os.chmod(file_name, stat.S_IWRITE)
For example:
import os
import stat
def clean_thrash(path):
dirlist=get_dirlist(path)
for f in dirlist:
fullname=os.path.join(path,f)
if fullname == os.path.join(path,"thrash.txt"):
os.chmod(fullname , stat.S_IWRITE)
os.remove(fullname)
if os.path.isdir(fullname):
clean_thrash(fullname)
I hope this fixes your problem.
If you are using windows, you can simply do:
import shutil
shutil.rmtree(directory_path)
Hope this works!
You have to be administrator user if you are on Windows or have to have sudo permissions if you are on Linux.
try running code with sudo
see this answer https://stackoverflow.com/a/32199615/6356497
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With