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

1.标准库参考:shutil.rmtree。

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

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

2.从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))

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

其中pth是pathlib.Path实例。很好,但可能不是最快的。

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()返回的元组。如果"忽略错误"为"假",而"OnError"为"无",则会引发异常。请在此处输入代码。

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

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

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:] == '
': 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])

从docs.python.org:

This example shows how to remove a directory tree on Windows where
some of the files have their read-only bit set. It uses the onerror
callback to clear the readonly bit and reattempt the remove.
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)

在删除之前检查文件夹是否存在,这样更可靠。

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

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

为了简单起见,可以使用os.system命令:

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

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

删除一个文件夹,即使它可能不存在(避免了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)

通过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。

使用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选项来显式处理非空的dir,那就方便了。

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

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

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

参考:

https://www.codenong.com/303200/

如何使用python移除/删除非空文件夹?的更多相关文章

  1. NodeJs递归删除非空文件夹

    此篇博文由于第一次使用fs.unlink()删除文件夹时报“Error: EPERM: operation not permitted, unlink”错误而写,这是因为fs.unlink()只能删除 ...

  2. 【转】 python 删除非空文件夹

    转自:https://blog.csdn.net/xiaodongxiexie/article/details/77155864 一般删除文件时使用os库,然后利用os.remove(path)即可完 ...

  3. python 删除非空文件夹

    import os import shutil os.remove(path) #删除文件 os.removedirs(path) #删除空文件夹 shutil.rmtree(path) #递归删除文 ...

  4. C 实现删除非空文件夹

    /* 文件名:   rd.c ---------------------------------------------------- c中提供的对文件夹操作的函数,只能对空文件夹进行 删除,这使很多 ...

  5. mac 下删除非空文件夹

    Linux中rmdir命令是用来删除空的目录.使用方式: rmdir [-p] dirName 参数: -p 是当子目录被删除后使它也成为空目录的话,则顺便一并删除. 举例说明:rmdir folde ...

  6. windows C++删除非空文件夹

    //add by zhuxy 递归删除文件夹 BOOL myDeleteDirectory(CString directory_path) //删除一个文件夹下的所有内容 { BOOL ret=TRU ...

  7. QT删除非空文件夹

    int choose; choose = QMessageBox::warning(NULL,"warning","确定删除该文件?",QMessageBox: ...

  8. shell命令rm删除非空文件夹

    rm -rf dirName CentOS的自带的资源管理器叫nautilus,在命令行里输入nautilus可以启动它.

  9. vc 递归删除非空文件夹

    我觉得这是一个非常不错的递归例子 头文件 #pragma once #include <atlstr.h> #include <io.h> #include <strin ...

随机推荐

  1. Fortify Audit Workbench 笔记 Race Condition: Singleton Member Field 竞争条件:单例的成员字段

    Race Condition: Singleton Member Field 竞争条件:单例的成员字段 Abstract Servlet 成员字段可能允许一个用户查看其他用户的数据. Explanat ...

  2. 使用MacOS自带的SVN客户端

    原文链接:https://jingyan.baidu.com/article/5552ef479c1554518ffbc92f.html 摘要:mac环境下有自带的SVN服务端和客户端,SVN是许多公 ...

  3. 使用types库修改函数

    import types class ppp: pass p = ppp()#p为ppp类实例对象 def run(self): print("run函数") r = types. ...

  4. 求100以内所有奇数的和,存于字变量X中。

    问题 求100以内所有奇数的和,存于字变量X中. 代码 data segment x dw ? data ends stack segment stack db 100 dup(?) stack en ...

  5. 7.12 NOI模拟赛 探险队 期望 博弈 dp 最坏情况下最优策略 可并堆

    LINK:探险队 非常难的题目 考试的时候爆零了 完全没有想到到到底怎么做 (当时去刚一道数论题了. 首先考虑清楚一件事情 就是当前是知道整张地图的样子 但是不清楚到底哪条边断了. 所以我们要做的其实 ...

  6. 7.9 NOI模拟赛 数列 交互 高精 字符串

    这是交互题 也是一个防Ak的题目 4个\(subtask\) 需要写3个不尽相同的算法. 题目下发了交互程序 所以调试的时候比较方便 有效防止\(CE\). 题目还有迷糊选手的点 数字位数为a 范围是 ...

  7. Win10系统安装MySQL Workbench 8

    系统:Window10 专业版 MySQL Workbench 8.0.19 下载地址:https://dev.mysql.com/downloads/workbench/8.0.html 点击Dow ...

  8. .NETCore微服务探寻(三) - 远程过程调用(RPC)

    前言 一直以来对于.NETCore微服务相关的技术栈都处于一个浅尝辄止的了解阶段,在现实工作中也对于微服务也一直没有使用的业务环境,所以一直也没有整合过一个完整的基于.NETCore技术栈的微服务项目 ...

  9. SpringBoot实现发送邮件

    1.QQ邮箱发送邮件设置 首先登录QQ邮箱>>>登录成功后找到设置>>>然后找到邮箱设置>>>点击账户>>>找到POP3|SMT ...

  10. C#LeetCode刷题之#217-存在重复元素(Contains Duplicate)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3772 访问. 给定一个整数数组,判断是否存在重复元素. 如果任何 ...