Python script to find largest files with given extension recursively

This simple Python script will list all filesĀ sorted by filesize in the given directory recursively. You must give anĀ -e/--extension argument to only consider specific filename extensions. Filename extensions are compared in a case-insensitive manner.

#!/usr/bin/env python3
import os
import argparse

def convert_size(size_bytes):
    """ Convert byte size to a human-readable format. """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']:
        if size_bytes < 1024:
            return f"{size_bytes:.2f}{unit}"
        size_bytes /= 1024
    return f"{size_bytes:.2f}YB"

def get_files_with_extensions(root_dir, extensions):
    """ Recursively find files with the given extensions in the directory. """
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if any(file.lower().endswith(ext.lower()) for ext in extensions):
                full_path = os.path.join(root, file)
                size = os.path.getsize(full_path)
                yield full_path, size

def main():
    parser = argparse.ArgumentParser(description="List files with specific extensions sorted by size.")
    parser.add_argument("directory", type=str, help="Directory to search")
    parser.add_argument("-e", "--extension", type=str, action='append', help="File extension to filter by", required=True)
    args = parser.parse_args()

    files = list(get_files_with_extensions(, args.extension))
    files.sort(key=lambda x: x[1])

    for file, size in files:
        print(f"{convert_size(size)} - {file}")

if __name__ == "__main__":

Usage example: Find largest Python files:

python -e py  .

Usage example: Find (some types of) movies:

python -e mov -e avi -e mkv -e mp4 ~/Nextcloud

Example output:

108.81MB - /home/uli/Nextcloud/Google Fotos/20220925_151542.mp4
117.92MB - /home/uli/Nextcloud/Google Fotos/20220925_151958.mp4
237.51MB - /home/uli/Nextcloud/Google Fotos/20220911_115209.mp4
265.02MB - /home/uli/Nextcloud/Google Fotos/20220905_151716.mp4
317.36MB - /home/uli/Nextcloud/Google Fotos/20220912_124906.mp4
431.06MB - /home/uli/Nextcloud/Google Fotos/20220921_153051.mp4