当我试图删除一个非空文件夹时,我得到一个“访问被拒绝”错误。我在尝试中使用了以下命令:os.remove("/folder_name")。

删除一个非空文件夹/目录最有效的方法是什么?


当前回答

我发现了一个非常简单的方法来删除任何文件夹(甚至不是空的)或文件在WINDOWS操作系统。

os.system('powershell.exe  rmdir -r D:\workspace\Branches\*%s* -Force' %CANDIDATE_BRANCH)

其他回答

如果你确定你想要删除整个目录树,并且不再对目录的内容感兴趣,那么爬行整个目录树是愚蠢的…只需从python中调用本机操作系统命令即可。它将更快,更有效,更少的内存消耗。

RMDIR c:\blah /s /q 

例如*那晚尼克斯。

rm -rf /home/whatever 

在python中,代码看起来像..

import sys
import os

mswindows = (sys.platform == "win32")

def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    if not mswindows:
        return commands.getstatusoutput(cmd)
    pipe = os.popen(cmd + ' 2>&1', 'r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts, text


def deleteDir(path):
    """deletes the path entirely"""
    if mswindows: 
        cmd = "RMDIR "+ path +" /s /q"
    else:
        cmd = "rm -rf "+path
    result = getstatusoutput(cmd)
    if(result[0]!=0):
        raise RuntimeError(result[1])

与操作系统。我提出的解决方案由3个一行Python调用组成:

python -c "import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]"
python -c "import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]"
python -c "import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)"

第一个脚本是chmod的所有子目录,第二个脚本是chmod的所有文件。然后第三个脚本移除所有障碍。

我已经从Jenkins作业中的“Shell脚本”中测试了这一点(我不想将新的Python脚本存储到SCM中,这就是为什么搜索一行解决方案),它适用于Linux和Windows。

您可以尝试下面的代码删除文件或文件夹,而不管它们是空的还是非空的。

import shutil
import os

directory = "path/to/the/root/folder"
files_in_directory = os.listdir(directory)

for file in files_in_directory:
    try:
        path_to_file_or_folder = os.path.join(directory, file)
        shutil.rmtree(path_to_file_or_folder)
    except:
        os.unlink(path_to_file_or_folder)
import os
import stat
import shutil

def errorRemoveReadonly(func, path, exc):
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        # change the file to be readable,writable,executable: 0777
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  
        # retry
        func(path)
    else:
        # raiseenter code here

shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly) 

如果设置了ignore_errors,错误将被忽略;否则,如果设置了onerror,则调用它来处理带有参数(func, path, exc_info)的错误,其中func是os。listdir,操作系统。Remove, or os.rmdir;Path是导致该函数失败的参数;exc_info是由sys.exc_info()返回的元组。如果ignore_errors为false且onerror为None,则会引发异常。在这里输入代码

对于Windows,如果目录不是空的,并且你有只读文件或者你会得到这样的错误

访问被拒绝 该进程无法访问该文件,因为它正被另一个进程使用

试试这个,os。system('rmdir /S /Q "{}"'.format(directory))

它相当于Linux/Mac中的rm -rf。