-->

Delete a current directory based on If condition

2019-08-21 10:42发布

问题:

Following code counts number of image in each sub directory. how to delete a sub directory if images in sub-directory are more than 2.
n13 is main directory=> which have 300 sub-directories(1...300)=> each sub-directory have images.

output:
Images:2, Directory:1
Images:3, Directory:2
Images:4, Directory:3

import os
path='C:/n13/'
def count_em(path):
    x = 0
    for root, dirs, files in os.walk(path):
       files_count = (len(files))
       x = x + 1
       print("Images:",files_count,"Directory:",x)
    return files_count

回答1:

You can use shutil.rmtree() to delete a folder with its sub-directories and files.

import os
import shutil

path='C:/n13/'

def count_em(path):
    x = 0
    files_count = 0
    for root, dirs, files in os.walk(path):
        files_count = (len(files))
        if files_count >= 2:
            shutil.rmtree(root)
        x = x + 1
        print("Images:", files_count, "Directory:", x)
    return files_count


count_em(path)