简体   繁体   English

PermissionError: [WinError 5] 访问被拒绝

[英]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每次我尝试在 Python 3.5.1 中使用os.remove()删除文件时,都会收到此消息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 .本质上,在调用os.remove(file_name)我们需要更改文件权限

  1. import stat
  2. Before calling os.remove , call os.chmod(file_name, stat.S_IWRITE)在调用os.remove之前,先调用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:如果您使用的是 Windows,您可以简单地执行以下操作:

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.如果你在 Windows 上,你必须是管理员用户,如果你在 Linux 上,则必须有 sudo 权限。 try running code with sudo尝试使用sudo运行代码

see this answer https://stackoverflow.com/a/32199615/6356497看到这个答案https://stackoverflow.com/a/32199615/6356497

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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