简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM