First, batch and shell
Directories and documents:
Copy Code code as follows:
C:\TESTFOLDER\TEST
├─test2
└─test3
Test.txt
Delete the directory and all the files under it:
Copy Code code as follows:
RMDIR/S/q C:\TestFolder\test
Deletes files in all directories, but the directory structure cannot be deleted:
Copy Code code as follows:
del/f/s/q c:\testfolder\test\*
Linux similar commands are:
Copy Code code as follows:
Second, in Python
: Note that if there are errors there will be exceptions thrown, you need to handle the exception.
1 Delete file and do not support wildcard characters: Os.remove ()
2 Delete Empty directory: Os.rmdir ()
3 Delete Empty directories and subdirectories: Os.removedirs ()
3 Delete the files in the directory and its subdirectories: Shutil.rmtree ()
Rmtree+ Exception Handling:
Copy Code code as follows:
#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 '
Using RmDir and remove is equivalent to Rmtree:
Copy Code code as follows:
#! /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 is 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}}}
Three, wildcard characters
Glob is Python's own file-operation-related module, which can be used to find files that match their own purposes, similar to file searches under Windows, support wildcard operations, *,?, [] These three wildcards, * represent 0 or more characters,? represents a character, [] Matches the specified range of characters, such as [0-9] matching digits.
Its main method is Glob, this method returns a list of all matching file paths that require a parameter to specify a matching path string (This string can be either an absolute or a relative path), and the filename returned includes only the file name in the current directory, excluding the files in the subfolder.