Hi, could you please modify this Python script to work recursively on images in…
- User
Hi, could you please modify this Python script to work recursively on images in subdirectories, instead of just images in the current working directory:
import glob from PIL import Image def find_smallest_pngs(): # Get all PNG files in the current directory image_files = glob.glob("*.[jJ][pP][gG]") + glob.glob("*.[pP][nN][gG]") + glob.glob("*.[wW][eE][bB][pP]") if not image_files: print("No image files found in the current directory.") return image_data = [] # Process each PNG file for file in image_files: try: with Image.open(file) as img: width, height = img.size pixel_count = width * height image_data.append((pixel_count, width, height, file)) except Exception as e: print(f"Skipping invalid file '{file}': {str(e)}") continue if not image_data: print("No valid PNG files could be processed.") return # Sort by pixel count (ascending) and select top 10 sorted_images = sorted(image_data, key=lambda x: x[0]) top_10 = sorted_images[:10] # Print results print("\nTop 10 smallest PNG images by pixel count (width × height):") print(f"{'Rank':<6} {'Filename':<50} {'Width':<8} {'Height':<8} {'Pixels':<10}") for idx, (pixels, w, h, name) in enumerate(top_10, 1): print(f"{idx:<6} {name[:47] + '...' if len(name) > 30 else name:<50} {w:<8} {h:<8} {pixels:<10}") if __name__ == "__main__": find_smallest_pngs() Assistant
Of course! Modifying the script to work recursively is a great idea and a common task. The most straightforward way to do this with the
globmodule is to use its recursive search feature.Here is the modified script. I'll explain the changes below.
Modified Python Script
import glob import os # Imported for better path handling, though not strictly required by the final glob solution from PIL import Image def find_smallest_pngs(search_dir="."): """ Recursively finds the 10 smallest image files (JPG, PNG, WEBP) in a directory and its subdirectories, based on pixel count. Args: search_dir (str): The top-level directory to start the search from. Defaults to the current directory. """ print(f"Searching for images in '{os.path.abspath(search_dir)}' and its subdirectories...") # Use recursive=True and the '**' pattern to search all subdirectories # The pattern '**/*.[ext]' finds files with the given extension in the # current directory and any subdirectory. image_files = ( glob.glob(os.path.join(search_dir, "**/*.[jJ][pP][gG]"), recursive=True) + glob.glob(os.path.join(search_dir, "**/*.[pP][nN][gG]"), recursive=True) + glob.glob(os.path.join(search_dir, "**/*.[wW][eE][bB][pP]"), recursive=True) ) if not image_files: print("No image files found in the specified directory or its subdirectories.") return image_data = [] total_files = len(image_files) # Process each image file for i, file in enumerate(image_files): # Provide some feedback for long-running scans print(f"\rProcessing file {i + 1}/{total_files}: {os.path.basename(file)}...", end="", flush=True) try: with Image.open(file) as img: width, height = img.size pixel_count = width * height image_data.append((pixel_count, width, height, file)) except Exception as e: # Print the error on a new line to not interfere with the progress indicator print(f"\nSkipping invalid file '{file}': {str(e)}") continue # Clear the progress line print("\n") if not image_data: print("No valid image files could be processed.") return # Sort by pixel count (ascending) and select top 10 sorted_images = sorted(image_data, key=lambda x: x[0]) top_10 = sorted_images[:10] # Print results print("Top 10 smallest images by pixel count (width × height):") # Adjusted column widths to better accommodate file paths print(f"{'Rank':<6} {'File Path':<65} {'Width':<8} {'Height':<8} {'Pixels':<10}") print("-" * 100) for idx, (pixels, w, h, name) in enumerate(top_10, 1): # Truncate the middle of the path if it's too long, which is often more useful display_name = name if len(name) > 62: display_name = name[:30] + "..." + name[-29:] print(f"{idx:<6} {display_name:<65} {w:<8} {h:<8} {pixels:<10}") if __name__ == "__main__": # You can optionally pass a directory to search, e.g., find_smallest_pngs("/path/to/your/images") find_smallest_pngs()
Summary of Key Changes
-
Recursive Glob Search:
- The core change is in the
glob.glob()calls. I added therecursive=Trueargument, which is available in Python 3.5 and later. - I modified the search pattern from
*.[ext]to**/*.[ext]. The**is a special pattern that, when used withrecursive=True, matches the current directory and all its subdirectories.
Before:
image_files = glob.glob("*.[jJ][pP][gG]")After:
image_files = glob.glob("**/*.[jJ][pP][gG]", recursive=True) - The core change is in the
-
Updated Status Messages:
- The message
No image files found in the current directory.was no longer accurate. I changed it to reflect that the script now searches subdirectories as well.
- The message
-
Improved User Experience (Optional but Recommended):
- Function Parameter: I wrapped the logic in a function
find_smallest_pngs(search_dir=".")that can now accept a path to search, making the script more flexible. - Progress Indicator: For recursive searches that might take a while, I added a simple progress indicator (
\r... end="") to show which file is being processed. - Better Output Formatting: Since filenames now include the directory path, they can be quite long. I adjusted the output table's column widths and added logic to intelligently truncate long paths so the table remains readable.
- Path Handling: Using
os.path.join()makes the script more robust across different operating systems (Windows, macOS, Linux).
- Function Parameter: I wrapped the logic in a function
This modified script is now more powerful and user-friendly, allowing you to easily scan entire directory trees for the smallest images.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.