user8463149
user8463149

Reputation:

Delete the same files inside multiple folders (python)

I have 100 folders with different names and each should be having the same three files inside it, but in some folders all these three files are not present.

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

These are the three files:

001.7z
002.7z
003.7z

Upvotes: 6

Views: 1671

Answers (2)

michael_heath
michael_heath

Reputation: 5372

Python using glob to get the 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. Could have used STD UDFs which might be less 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)

Upvotes: 3

Itamar
Itamar

Reputation: 76

First of all get a list of all directories within the folder:

import shutil
import os

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

run on all folder look for the specific files matches the filenames mentioned(complete 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

Upvotes: 0

Related Questions