first, batch and Shell
Directories and files:
The code is as follows:
C:\TESTFOLDER\TEST
├─test2
└─test3
Test.txt
Delete the directory and all files under it:
The code is as follows:
RMDIR/S/q C:\TestFolder\test
Delete files from all directories, but the directory structure cannot be deleted:
The code is as follows:
del/f/s/q c:\testfolder\test\*
Linux-like commands are:
The code is as follows:
Rm/rf/home/aaa/test
Second, in Python
: Note that if there is an exception thrown with an error, you need to handle the exception.
1) Delete the 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:
The code is 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:
The code is 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 being empty.
The starting directory is not deleted.
Written by:anand B Pillai "" "
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 a file operation related module of Python itself, it can find files for its own purposes, similar to the file search under Windows, support wildcard operation, *,?, [] These three wildcards, * represents 0 or more characters,? represents a character, [] Matches a character within a specified range, such as [0-9] matches a number.
Its main method is Glob, which returns a list of all matching file paths, which requires a parameter to specify a matching path string (This string can be either an absolute path or a relative path), and its returned file name includes only the filename in the current directory, not the files in the subfolder.