Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PermissionError: [WinError 5] Access is denied

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.

like image 651
Saraghu Ravi Avatar asked May 22 '16 17:05

Saraghu Ravi


3 Answers

I too had this problem, and after searching found a good solution.

Essentially, before calling os.remove(file_name) we need change file permissions.

  1. import stat
  2. Before calling 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.

like image 58
Enrique Nieto Avatar answered Oct 23 '22 04:10

Enrique Nieto


If you are using windows, you can simply do:

import shutil
shutil.rmtree(directory_path)

Hope this works!

like image 27
Ghantey Avatar answered Oct 23 '22 05:10

Ghantey


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

like image 1
Revaz Shalikashvili Avatar answered Oct 23 '22 04:10

Revaz Shalikashvili