删除多个文件夹中的相同文件 (python)

Delete the same files inside multiple folders (python)

我有 100 个不同名称的文件夹,每个文件夹中应该包含相同的三个文件,但在某些文件夹中,这三个文件都不存在。

如何删除那些空文件夹或只包含一个或两个文件的文件夹?

这是三个文件:

001.7z
002.7z
003.7z

首先获取文件夹内所有目录的列表:

import shutil
import os

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

运行 在所有文件夹中查找与提到的文件名匹配的特定文件(完成这部分..):

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

Python 使用 glob 获取文件和文件夹。

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)

A​​utoIt 使用 FileFindFirstFile。可以使用可能更少代码的 STD UDF。

$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)