Find Images Larger Than 500 KB Recursively with python

Large images in an exported web project can increase loading time. This script recursively scans a directory and writes paths for images larger than 500 KB to large_images.txt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import os

def find_large_images(directory, size_limit_kb, output_file):
    with open(output_file, 'w', encoding='utf-8') as output:
        for root, _, files in os.walk(directory):
            for name in files:
                path = os.path.join(root, name)
                size_kb = os.path.getsize(path) / 1024
                is_image = name.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))
                if is_image and size_kb > size_limit_kb:
                    output.write(path + '\n')

if __name__ == '__main__':
    directory = input('Directory to scan: ')
    find_large_images(directory, 500, 'large_images.txt')
    print('Finished. Results were saved to large_images.txt')