Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Remove specific extensions

Updated: 21 dec 2025

This code deletes files with specific extensions inside a folder and its subfolders.

  • Parameters:

    • root_folder (str): Path to the main directory.

    • extensions (list or set): File extensions to delete, e.g. [‘.jpg’, ‘.pdf’]

import os

path = 'C:/test'
extensions = ["jpg", "pdf"]

def delete_file_types(root_folder, extensions):

    extensions = {ext if ext.startswith('.') else '.' + ext for ext in extensions}

    removed_files = []

    for folder, _, files in os.walk(root_folder):
        for filename in files:
            if any(filename.lower().endswith(ext) for ext in extensions):
                file_path = os.path.join(folder, filename)
                try:
                    os.remove(file_path)
                    removed_files.append(file_path)
                    print(f"Deleted: {file_path}")
                except Exception as e:
                    print(f"Failed to delete {file_path}: {e}")

    print("\nDone.")
    print(f"Total deleted files: {len(removed_files)}")

delete_file_types(path, extensions)