Examples of using glob and Rmtree to delete directory subdirectories and all files in Python _python

Source: Internet
Author: User
Tags glob in python

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:

Rm/rf/home/aaa/test

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.