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

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


#1楼

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

#2楼

import os
import stat
import shutildef 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: 0777os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # retryfunc(path)else:# raiseenter code hereshutil.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 pathlibdef 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 shutilshutil.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 existsif os.path.exists(path):# remove if existsshutil.rmtree(path)else:# throw your exception to handle this special scenarioraise 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 subdirectoryext = (".srt", ".txt")contains_other_ext=0for file in files:if not file.endswith(ext):  contains_other_ext=Trueif 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 = 0for 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_sizereturn totalfor dir, subdirs, files in os.walk(root):   If get_tree_size(dir) < 400000:  # ≈ 400kbsend2trash(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 shutildef ignore_absent_file(func, path, exc_inf):except_instance = exc_inf[1]if isinstance(except_instance, FileNotFoundError):returnraise except_instanceshutil.rmtree(dir_to_delete, onerror=ignore_absent_file)

Python 2.7代码几乎相同:

import shutil
import errnodef ignore_absent_file(func, path, exc_inf):except_instance = exc_inf[1]if isinstance(except_instance, OSError) and \except_instance.errno == errno.ENOENT:returnraise except_instanceshutil.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 osmswindows = (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 = 0if text[-1:] == '\n': text = text[:-1]return sts, textdef deleteDir(path):"""deletes the path entirely"""if mswindows: cmd = "RMDIR "+ path +" /s /q"else:cmd = "rm -rf "+pathresult = 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 Uniondef 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():continuep.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上运行)
  • 如果需要,可以进行非常精细的日志记录,例如,在发生时记录每个删除。

如何删除/删除Python不为空的文件夹?相关推荐

  1. 服务器空文件夹无法删除怎么办,空的文件夹无法删除怎么办 空的文件夹无法删除的原因【图文】...

    电脑已经不是人们生活中所陌生的产品,现在人们的娱乐.办公都会用到电脑,而在电脑被越发使用频繁的当下,出现的问题相对来说就越多了.很多时候这些小问题,却使得人们在使用电脑的过程中碰到大难题.就好比空的文 ...

  2. C#、 Unity 删除空的文件夹

    一键删除所有的空的文件夹 /**** * * 删除空文件夹* */using System.Collections.Generic; using System.IO; using UnityEdito ...

  3. win10计算机里文件夹怎么删除文件,如何删除win10“此电脑”中6个文件夹?

    更新完win10系统,我们会发现打开"此电脑",相比win7相比,除了还有传统的硬盘分区外,还多了6个文件夹:视频.图片.文档.下载.音乐和桌面.讲真,这些文件夹似乎也用不上,对于 ...

  4. 如何恢复计算机隐藏的文件夹,电脑文件夹删除了怎么恢复 电脑隐藏的文件夹怎么找到...

    我们在使用电脑的时候难免会有误操作的时候,比如我们想清丽电脑中的垃圾文件,不小心将一个重要的文件一起删除了,这时候我们只能想办法恢复吧!可是怎么恢复呢?其实很简单,下面小编为大家带来文件夹误删除的详细 ...

  5. Python的os模块常用文件夹的增删改查详解

    python常用os模块 增 os.makedirs("path\\目录") 用于递归创建目录 删 os.remove("path")用于删除指定路径(path ...

  6. 使用Python设计一个自动查询文件夹的exe文件

    使用Python设计一个自动查询文件夹的exe文件 文章目录 使用Python设计一个自动查询文件夹的exe文件 前言 一.消灭噩梦(~~摸鱼~~ )的开始 二.~~摸鱼~~ 效果升级--添加拷贝功能 ...

  7. 用迅雷下载的视频,文件夹打开是空的,文件夹有大小,也没有隐藏文件的解决办法

    用迅雷下载的视频,文件夹打开是空的,文件夹有大小,也没有隐藏文件的解决办法 如果有2个文件名一样的,删除其中那个是0大小的,则另一位文件夹就有东西了.

  8. Python自动化办公学习- 获取文件夹下的所有文档的名字并存储到Excel

    Python自动化办公学习- 获取文件夹下的所有文档的名字并存储到Excel 这是我第一次学习使用csdn发布学习笔记,如有版权侵犯,引用不当的地方,请立即提示我,我会删除,谢谢. 笔记中如有解释错误 ...

  9. Python 创建随机名字的文件夹/文件

    Python 创建随机名字的文件夹/文件 导入库 创建文件名 创建文件 导入库 import random import string import os 创建文件名 dir_name = ''.jo ...

最新文章

  1. 将信息系学生的计算机文化学,计算机学生论文,关于基于职业岗位的计算机文化基础课教学相关参考文献资料-免费论文范文...
  2. 车联网支持实现无人驾驶的思考
  3. 使用CATT作批量数据导入
  4. Linux tar vi gcc 指令
  5. Distance on the tree(树上倍增+主席树+树上差分+lca)南昌网络赛
  6. Linux编程(2)_软件的安装和卸载
  7. bzoj 5016: [Snoi2017]一个简单的询问(莫队)
  8. python的简单实用小工具(未完待续......)
  9. Access数据库的模糊查询
  10. vb access mysql_vb连接access数据库
  11. docker安装gamit_科学网-基于Ubuntu18.04安装Gamit10.71-郭若成的博文
  12. nginx服务器添加微信小程序校验文件
  13. 迅雷如何添加html文件夹,迅雷7上我的收藏怎么找
  14. 《从0到1上线微信小游戏》第七节 微信排行榜和好友分享功能
  15. python+selenium打开浏览器-设置浏览器路径和驱动器路径
  16. 现代电子计算机本质工作原理,现代电子计算机的本质工作原理是()。
  17. OSC职位推荐:DJI 大疆创新,只招聘偏执狂
  18. 推荐一些有趣的编程书籍和电影
  19. HTTPServerMock从手工到平台的演变
  20. 解析全球热点脑机接口平台(下)

热门文章

  1. 【Java基础】Java中的char是否可以存储一个中文字符之理解字符字节以及编码集
  2. python time 时钟计时_如何使用Python的timeit计时代码段以测试性能?
  3. ConcurrentHashMap源码分析(1)——JDK1.7的实现
  4. Android性能优化典范第四季
  5. 【Gradle】借助gradle的ProductFlavor实现多App间代码库复用
  6. android中实现返回首页功能
  7. Swift JSON转模型Xcode插件
  8. swift_021(Swift 的方法)
  9. rs485协议_你知道HART和RS485协议的区别吗?
  10. LeetCode 75. 颜色分类(Sort Colors)