Delete Many Folders At Once in Python

This is useful if say the package you're experimenting with generates a folder of results every time you run it to test it.

import os, shutil
folder = '<folder_path>'
to_delete= [item for item in os.listdir(folder) if item!="important.txt"]
for filename in to_delete:
    file_path= os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))

In case you have a directory of folders only,

import os, shutil
path= "parent_directory_path"
for folder in os.listdir(path):
    try:
        shutil.rmtree(folder)
    except Exception as e:
        print('Failed to delete %s. Reason is %s' % (file_path, e))

Last updated