刪除指定目錄下包含指定名稱的文件夾(遞歸) python


在整理mfc程序的時候, 為了清理項目資源, 經常需要刪除項目目錄或其子目錄下(遞歸)的Debug, Release, x64, .vs等文件目錄, 如果有很多項目, 手工清理很是麻煩, bat不太熟悉, 沒找到合適的腳本, 自己用python寫了一個清理的小腳本,

使用用例:

python demo.py CleanDir Debug, Release, x64, .vs

 1 import os
 2 import sys
 3 
 4 def DelDirAndSubDirByName(rootPath, dirNameList):
 5     subPath = ''
 6     for item in os.listdir(rootPath):
 7         subPath = rootPath + '\\' + item
 8         if os.path.isdir(subPath):
 9             if item in dirNameList:
10                 DelAllFile(subPath)
11                 print('del dir: %s' %(subPath))
12             else:
13                 DelDirAndSubDirByName(subPath, dirNameList)
14 
15 def DelAllFile(delPath):
16     if os.path.isfile(delPath):
17         os.remove(delPath)
18     else:
19         for item in os.listdir(delPath):
20             DelAllFile(delPath + '\\' + item)
21         os.rmdir(delPath)  
22 
23 if __name__ == '__main__':
24     if  len(sys.argv) < 2 or \
25         sys.argv[1] == '/?' or \
26         sys.argv[1] == '-h' or \
27         sys.argv[1] == '--help':
28         print('usage: exe.py delPath delDirName1 delDirName2 ...')
29         exit(0)
30 
31     delPath = os.path.abspath(sys.argv[1])
32     print(delPath)
33     if os.path.exists(delPath) != True:
34         print('%s is not exist' %(delPath))
35         exit(1)
36 
37     if os.path.isdir(delPath) != True:
38         print('%s is not dir' %(delPath))
39         exit(2)
40 
41     dirNameList = sys.argv[2:]
42     DelDirAndSubDirByName(delPath, dirNameList)

 


免責聲明!

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



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