Delete the same files inside multiple folders (python)

I have 100 folders with different names, and each of them should have the same three files inside it, but in some folders all these three files are missing.

How can I delete folders that are empty or contain only one or two files?

These are three files:

001.7z 002.7z 003.7z 
+5
source share
2 answers

Python using glob to get files and folders.

 import glob, os, shutil # Get all folders in current directory. folders = [item for item in glob.iglob('*') if os.path.isdir(item)] # Loop though the folders. for folder in folders: # Check amount of .7z files and if less than 3, remove folder tree. if len(glob.glob(folder + r'\*.7z')) < 3: shutil.rmtree(folder) 

AutoIt using FileFindFirstFile . Perhaps they used STD UDF, which may be less than code.

 $hFind1 = FileFindFirstFile('*') If $hFind1 = -1 Then Exit 1 While 1 ; Get next folder. $sFound1 = FileFindNextFile($hFind1) If @error Then ExitLoop ; Skip files. If Not @extended Then ContinueLoop ; Find 7z files. $hFind2 = FileFindFirstFile($sFound1 & '\*.7z') ; If no handle, delete folder. If $hFind2 = -1 Then DirRemove($sFound1) ContinueLoop EndIf ; Count for 7z files. $iCount = 0 ; Get count of 7z files. While 1 $sFound2 = FileFindNextFile($hFind2) If @error Then ExitLoop $iCount += 1 WEnd FileClose($hFind2) ; Remove folder if count less than 3. If $iCount < 3 Then DirRemove($sFound1, 1); 1 = recurse EndIf WEnd FileClose($hFind1) 
+2
source

First of all, get a list of all the directories in the folder:

 import shutil import os dirs = filter(os.path.isdir, os.listdir(os.curdir)) 

run in all folders the search for specific files matches the specified file names (fill in this part ..):

 for dir in dirs: files = filter(os.path.isfile, os.listdir(str(os.curdir) + dir)) for file in files: if file=="01.7z": ##Continue here shutil.rmtree(str(os.curdir) + dir) break 
0
source

Source: https://habr.com/ru/post/1276063/


All Articles