空フォルダ一覧を削除するバッチファイルを作るスクリプト
pythonを使って、空フォルダを一覧を作成し、空フォルダ削除するバッチファイルを出力するスクリプトを作った。
python check_folder.py "チェックしたいフォルダパス" "出力するバッチファイル"
check_folder.py
import sys import glob import os def getFileList(folder_path): # 最後が\\じゃなかった場合追加 if folder_path[len(folder_path)-1] !="\\": folder_path = folder_path + "\\" search_path = folder_path +"*" filepaths = glob.glob(search_path) return filepaths def main() : print("main") # ファイルがないフォルダを探す def CheckExistFilesInFolder(folder_path_list,no_exist_file_in_folder_list): # このフォルダリストにファイルが存在するか isFileExist=False for folder_path in folder_path_list: folder_check = folder_path if folder_check[len(folder_check)-1] !="\\": folder_check = folder_check + "\\" folder_check = folder_check + "*" # フォルダの中のファイルを検索 file_list = glob.glob(folder_check) folder_sub_list = [] # フォルダのファイルとフォルダをチェック、フォルダがあればfolder_sub_listに追加 file_count = 0 for file_path in file_list: if os.path.isdir(file_path): folder_sub_list.append(file_path) else: file_count = file_count +1 # サブフォルダにもファイルは存在しない IsSubFolderFileExist = False # フォルダパスが存在する場合 if len(folder_sub_list)>0: no_exist_file_in_folder_list,IsSubFolderFileExist = CheckExistFilesInFolder(folder_sub_list,no_exist_file_in_folder_list) # フォルダにファイルが存在しない && サブフォルダにも存在しない場合 if file_count==0 and IsSubFolderFileExist==False: no_exist_file_in_folder_list.append(folder_path) else: ''' if file_count >0: print("FileHit! : ",folder_path) else: print("SubFolder have file:",folder_path) ''' isFileExist = True # ファイルが存在しないフォルダ一覧と、渡されたフォルダ一覧にファイルがあったかを返す return no_exist_file_in_folder_list,isFileExist # mainのコード if __name__ == '__main__': args = sys.argv print(args) print("args len :",len(args)) folder_path ="" out_file_path ="" if len(args) > 1 : folder_path = args[1] else : print("Please Folder Path > ") folder_path = input() if len(args) > 2: out_file_path = args[2] else: print("Please output file>") out_file_path = input() filepaths = getFileList(folder_path) # フォルダだけ抽出 folder_list = [] for one_path in filepaths: if os.path.isdir(one_path) == True: folder_list.append(one_path) no_exist_file_in_folder_list = [] # 空フォルダの抽出 no_exist_file_in_folder_list ,isFileExist = CheckExistFilesInFolder(folder_list,no_exist_file_in_folder_list) file_io = open(out_file_path,"w") file_io.write("echo Delete ?") file_io.write("\n") file_io.write("pause") file_io.write("\n") for folderList in no_exist_file_in_folder_list: message ="rd /s /Q \"" + folderList +"\"" file_io.write(message) file_io.write("\n") file_io.write("pause") file_io.write("\n") file_io.close() print("-----------------") print("isFileExist:",isFileExist)