python實例32[glob+rmtree來刪除目錄和子目錄及其下所有文件]


一 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 

 

完! 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM