Examples of using glob and rmtree in Python to delete subdirectories and all files from a directory
- 2020-04-02 14:24:17
- OfStack
Batch and shell
Directories and files:
C:TESTFOLDERTEST
├ ─ Test2
└ ─ Test3
test.txt
Delete all files under the directory:
rmdir /S /Q c:TestFoldertest
Delete all files in the directory, but the directory structure cannot be deleted:
del /F /S /Q c:TestFoldertest*
Linux's similar command is:
rm /rf /home/aaa/test
Second, in python
: note that an exception will be thrown if an error occurs.
1) delete files and do not support the wildcard: os.remove()
2) delete the empty directory: os.rmdir()
3) remove empty directories and subdirectories: os.removedirs()
3) delete files in the directory and its subdirectories: shutil.rmtree()
Rmtree + exception handling:
#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:testfoldertestTest3
[Error 32] The process cannot access the file because it is being used by another process: 'c:\testfolder\test\Test3'
Error:c:testfoldertest
[Error 145] The directory is not empty: 'c:\testfolder\test'
Using rmdir and remove is equivalent to 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 }}}
wildcards
Glob is python's own file operation-related module that allows you to find files that fit your purpose, similar to file search in Windows, and supports wildcard operations. ,[], * for 0 or more characters, ? Represents a character that [] matches a character in a specified range, such as [0-9] matches a number.
Its main way is glob, this method returns all matching path to the file list, this method needs a parameter used to match the specified path string (this string can be as an absolute path is a relative path), which returns the file name including the file name in the current directory only, do not include a folder in the file.