python[glob+rmtree来删除目录和子目录及其下所有文件]
2016-12-29 13:43
826 查看
一 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,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
参考:http://xiagu1.iteye.com/blog/619526
目录及文件:
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,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
参考:http://xiagu1.iteye.com/blog/619526
相关文章推荐
- Python批量对目录下文件重命名
- python 2.7 : 错误处理、调试
- python实例手册
- python 实现递归删除文件和文件夹
- python之基础篇(五)——数据类型
- numpy的 Broadcasting
- pycharm把.py文件识别成.text文件
- Python 错误:IndentationError: expected an indented block
- Python3:好玩游戏的物品清单 和 列表到字典的函数
- 理解Python闭包与延迟绑定
- tornado 入门
- Python编程的中文问题
- caffe+python+mnist从图片训练到测试单张图片
- caffe+python+mnist从图片训练到测试单张图片
- python学习笔记(三)
- Python3 基础:模块
- 操作系统课程设计-线程和进程的同步与互斥
- python2与python3区别汇总
- Cassandra3.9版本基础入门3-插入和查询
- 深度解析minist例子(lasagne)