PermissionError: [WinError 5] 访问被拒绝

Sar*_*avi 6 python python-3.x

每次我尝试删除os.remove()Python 3.5.1 中使用的文件时,都会收到此消息PermissionError: [WinError 5] Access is denied

这是简单的代码:

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)
Run Code Online (Sandbox Code Playgroud)

甚至没有删除目录或子目录中的单个文件。

小智 11

如果您使用的是 Windows,您可以简单地执行以下操作:

import shutil
shutil.rmtree(directory_path)
Run Code Online (Sandbox Code Playgroud)

希望这有效!


小智 5

我也遇到了这个问题,经过搜索找到了一个很好的解决方案。

本质上,在调用之前os.remove(file_name)我们需要更改文件权限

  1. import stat
  2. 打电话之前os.remove,先打电话os.chmod(file_name, stat.S_IWRITE)

例如:

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)
Run Code Online (Sandbox Code Playgroud)

我希望这可以解决您的问题。


Rev*_*ili 1

如果您使用的是 Windows,则必须是管理员用户;如果您使用的是 Linux,则必须具有 sudo 权限。尝试运行代码sudo

看到这个答案/sf/answers/2253973081/