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

这篇博客讨论了在Python中删除非空文件夹时遇到的问题和解决方案,包括使用`shutil.rmtree()`、处理只读文件的方法以及跨平台的删除策略。提供了多种不同方法,包括设置`onerror`回调、使用`os`模块和`pathlib`等。
摘要由CSDN通过智能技术生成

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

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


#1楼

import shutil
shutil.rmtree(dest, ignore_errors=True)

#2楼

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,则会引发异常。请输入此处的代码


#3楼

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

其中pthpathlib.Path实例。 不错,但可能不是最快的。


#4楼

import shutil

shutil.rmtree('/folder_name')

标准库参考:shutil.rmtree

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

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

#5楼

os.walk()的python文档

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

#6楼

根据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")

#7楼

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

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

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


#8楼

如果您不想使用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

#9楼

只需一些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")

#10楼

来自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) 

#11楼

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

对于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)

#12楼

如果你确定,你想要删除整个目录树,并且对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])

#13楼

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)

#14楼

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

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

#15楼

使用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。


#16楼

十年后,使用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选项来显式处理非空目录,那将会很方便。


#17楼

对于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


#18楼

我想添加一个“纯粹的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
        p.chmod(0o666)
        if p.is_dir():
            p.rmdir()
        else:
            if only_if_empty:
                raise RuntimeError(f'{p.parent} is not empty!')
            p.unlink()
    target.rmdir()

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

优点:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值