Python中使用glob和rmtree删除目录子目录及所有文件的例子
作者:junjie 时间:2023-12-26 07:14:18
一、batch与shell中
目录及文件:
C:\TESTFOLDER\TEST
├─Test2
└─Test3
test.txt
删除目录及其下的所有文件:
rmdir /S /Q c:\TestFolder\test
删除所有目录下的文件,但是目录结构不能被删除:
del /F /S /Q c:\TestFolder\test\*
Linux类似的命令为:
rm /rf /home/aaa/test
二、python中
:注意如果有错误会有异常抛出,需要处理异常。
1)删除文件且不支持通配符: os.remove()
2) 删除空的目录: os.rmdir()
3) 删除空的目录及子目录: os.removedirs()
3) 删除目录及其子目录中的文件:shutil.rmtree()
rmtree+异常处理:
#code:
import shutil
def retreeExceptionHandler(fun,path,excinfo):
print("Error:" + path)
print(excinfo[1])
shutil.rmtree('c:\\testfolder\\test',ignore_errors=False,onerror=retreeExceptionHandler)
#result:
Error:c:\testfolder\test\Test3
[Error 32] The process cannot access the file because it is being used by another process: 'c:\\testfolder\\test\\Test3'
Error:c:\testfolder\test
[Error 145] The directory is not empty: 'c:\\testfolder\\test'
使用rmdir和remove等价于rmtree:
#! /usr/bin/env python
#coding=utf-8
## {{{ Recipe 193736 (r1): Clean up a directory tree
""" removeall.py:
Clean up a directory tree from root.
The directory need not be empty.
The starting directory is not deleted.
Written by: Anand B Pillai <abpillai@lycos.com> """
import sys, os
ERROR_STR= """Error removing %(path)s, %(error)s """
def rmgeneric(path, __func__):
try:
__func__(path)
print 'Removed ', path
except OSError, (errno, strerror):
print ERROR_STR % {'path' : path, 'error': strerror }
def removeall(path):
if not os.path.isdir(path):
return
files=os.listdir(path)
for x in files:
fullpath=os.path.join(path, x)
if os.path.isfile(fullpath):
f=os.remove
rmgeneric(fullpath, f)
elif os.path.isdir(fullpath):
removeall(fullpath)
f=os.rmdir
rmgeneric(fullpath, f)
## End of recipe 193736 }}}
三、通配符
glob是python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,支持通配符操作,*,?,[]这三个通配符,*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。
它的主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
标签:python,glob,rmtree,删除目录,子目录
0
投稿
猜你喜欢
23个很棒的Python脚本集合分享(迷你项目)
2023-12-24 04:34:15
ASP 验证码的程序及原理
2010-04-24 15:56:00
sqlserver 高性能分页实现分析
2024-01-29 03:56:11
Python OpenCV超详细讲解读取图像视频和网络摄像头
2023-11-26 05:22:36
MySQL忘记密码恢复密码的实现方法
2024-01-19 08:55:14
从零开始搭建MySQL MMM架构
2024-01-17 12:40:23
javascript实现自动输出文本(打字特效)
2024-02-25 18:25:14
特殊字符的json序列化总结大全
2023-12-04 00:36:58
基于javascript实现表格的简单操作
2024-04-30 08:55:24
python3.6.3转化为win-exe文件发布的方法
2021-02-16 05:57:40
微信小程序 滚动选择器(时间日期)详解及实例代码
2024-01-27 22:57:53
python使用Matplotlib绘制分段函数
2022-04-17 16:07:17
python3列表删除大量重复元素remove()方法的问题详解
2021-02-02 19:26:03
python3 判断列表是一个空列表的方法
2022-02-03 09:40:07
Python根据已知邻接矩阵绘制无向图操作示例
2023-04-26 18:53:27
正则表达式结合数组提取文章中的文件名
2007-10-12 13:59:00
使用 use re debug 查看正则表达式的匹配过程
2022-05-03 01:00:59
如何在Python中安装GDAL库
2023-08-22 01:51:54
Golang排列组合算法问题之全排列实现方法
2023-07-14 14:16:19
实例讲解Python脚本成为Windows中运行的exe文件
2023-07-15 02:14:31