如何删除/删除Python不为空的文件夹?

问题描述 投票:753回答:18

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

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

python file
18个回答
1211
投票
import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree

根据设计,rmtree在包含只读文件的文件夹树上失败。如果要删除文件夹而不管它是否包含只读文件,请使用

shutil.rmtree('/folder_name', ignore_errors=True)

3
投票

如果您不想使用shutil模块,可以使用os模块。

from os import listdir, rmdir, remove
for i in listdir(directoryToRemove):
    os.remove(os.path.join(directoryToRemove, i))
rmdir(directoryToRemove) # Now the directory is empty of files

2
投票

您可以使用os.system命令来简化:

import os
os.system("rm -rf dirname")

很明显,它实际上调用系统终端来完成这项任务。


2
投票

要删除文件夹,即使它可能不存在(避免Charles Chow's answer中的竞争条件)但在其他事情出错时仍然有错误(例如权限问题,磁盘读取错误,文件不是目录)

对于Python 3.x:

import shutil

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, FileNotFoundError):
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

Python 2.7代码几乎相同:

import shutil
import errno

def ignore_absent_file(func, path, exc_inf):
    except_instance = exc_inf[1]
    if isinstance(except_instance, OSError) and \
        except_instance.errno == errno.ENOENT:
        return
    raise except_instance

shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

2
投票
def deleteDir(dirPath):
    deleteFiles = []
    deleteDirs = []
    for root, dirs, files in os.walk(dirPath):
        for f in files:
            deleteFiles.append(os.path.join(root, f))
        for d in dirs:
            deleteDirs.append(os.path.join(root, d))
    for f in deleteFiles:
        os.remove(f)
    for d in deleteDirs:
        os.rmdir(d)
    os.rmdir(dirPath)

1
投票

使用os.walk我会提出由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。


1
投票

十年后,使用Python 3.7和Linux仍有不同的方法:

import subprocess
from pathlib import Path

#using pathlib.Path
path = Path('/path/to/your/dir')
subprocess.run(["rm", "-rf", str(path)])

#using strings
path = "/path/to/your/dir"
subprocess.run(["rm", "-rf", path])

本质上,它使用Python的子进程模块来运行bash脚本$ rm -rf '/path/to/your/dir,就像使用终端完成相同的任务一样。它不是完全的Python,但它完成了它。

我加入pathlib.Path示例的原因是因为根据我的经验,它在处理许多改变的路径时非常有用。导入pathlib.Path模块并将最终结果转换为字符串的额外步骤通常对我来说开发时间成本较低。如果Path.rmdir()附带一个arg选项来明确处理非空目录,那将会很方便。


0
投票

我找到了一种非常简单的方法来删除WINDOWS OS上的任何文件夹(甚至不是空)或文件。

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

0
投票

对于Windows,如果目录不为空,并且您有只读文件或者出现类似错误

  • Access is denied
  • The process cannot access the file because it is being used by another process

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

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


0
投票

我想添加一个“纯粹的pathlib”方法:

from pathlib import Path
from typing import Union

def del_dir(target: Union[Path, str], only_if_empty: bool = False):
    target = Path(target).expanduser()
    assert target.is_dir()
    for p in sorted(target.glob('**/*'), reverse=True):
        if not p.exists():
            continue
        if p.is_dir():
            p.chmod(0o666)
            p.rmdir()
        else:
            if only_if_empty:
                raise RuntimeError(f'{p.parent} is not empty!')
            p.chmod(0o666)
            p.unlink()
    target.rmdir()

这取决于Path是可订购的事实,而较长的路径将始终按照较短的路径排序,就像str一样。因此,目录将在文件之前。如果我们反转排序,文件将在各自的容器之前,所以我们可以通过一次传递简单地取消链接/ rmdir。

优点:

  • 它不依赖于外部二进制文件:一切都使用Python的电池包含的模块(Python> = 3.6)
  • 它快速且内存效率高:没有递归堆栈,无需启动子进程
  • 它是跨平台的(至少,这是pathlib在Python 3.6中承诺的;上面没有说明的操作不在Windows上运行)
  • 如果需要,可以进行非常精细的日志记录,例如,在发生时记录每个删除。

129
投票

来自the python docsos.walk()

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

103
投票
import shutil
shutil.rmtree(dest, ignore_errors=True)

17
投票

从python 3.4你可以使用:

import pathlib

def delete_folder(pth) :
    for sub in pth.iterdir() :
        if sub.is_dir() :
            delete_folder(sub)
        else :
            sub.unlink()
    pth.rmdir() # if you just want to delete dir content, remove this line

其中pth是一个pathlib.Path实例。不错,但可能不是最快的。


7
投票
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,os.remove或os.rmdir; path是导致它失败的那个函数的参数;和exc_info是sys.exc_info()返回的元组。如果ignore_errors为false且onerror为None,则会引发异常。请输入此处的代码


6
投票

如果你确定,你想要删除整个目录树,并且对dir的内容不再感兴趣,那么爬行整个目录树就是愚蠢......只需从python调用本机OS命令就可以了。它将更快,更高效,更少内存消耗。

RMDIR c:\blah /s /q 

或者* nix

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])

5
投票

来自docs.python.org

此示例显示如何在Windows上删除某些文件的只读位设置的目录树。它使用onerror回调清除readonly位并重新尝试删除。任何后续故障都会传播。

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)

5
投票

只需一些python 3.5选项即可完成上述答案。 (我很想在这里找到它们)。

import os
import shutil
from send2trash import send2trash # (shutil delete permanently)

删除文件夹,如果为空

root = r"C:\Users\Me\Desktop\test"   
for dir, subdirs, files in os.walk(root):   
    if subdirs == [] and files == []:
           send2trash(dir)
           print(dir, ": folder removed")

如果它包含此文件,也删除它

    elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file 
        if files[0]== "desktop.ini" or:  
            send2trash(dir)
            print(dir, ": folder removed")
        else:
            print(dir)

删除文件夹,如果它只包含.srt或.txt文件

    elif subdirs == []: #if dir doesn’t contains subdirectory
        ext = (".srt", ".txt")
        contains_other_ext=0
        for file in files:
            if not file.endswith(ext):  
                contains_other_ext=True
        if contains_other_ext== 0:
                send2trash(dir)
                print(dir, ": dir deleted")

删除文件夹,如果其大小小于400kb:

def get_tree_size(path):
    """Return total size of files in given path and subdirs."""
    total = 0
    for entry in os.scandir(path):
        if entry.is_dir(follow_symlinks=False):
            total += get_tree_size(entry.path)
        else:
            total += entry.stat(follow_symlinks=False).st_size
    return total


for dir, subdirs, files in os.walk(root):   
    If get_tree_size(dir) < 400000:  # ≈ 400kb
        send2trash(dir)
    print(dir, "dir deleted")

5
投票

根据kkubasik的答案,在删除之前检查文件夹是否存在,更加健壮

import shutil
def remove_folder(path):
    # check if folder exists
    if os.path.exists(path):
         # remove if exists
         shutil.rmtree(path)
    else:
         # throw your exception to handle this special scenario
         raise XXError("your exception") 
remove_folder("/folder_name")
© www.soinside.com 2019 - 2024. All rights reserved.