Convert All Your Images to WebP (Python Script)

TL;DR • 3 min read
  • WebP gives up to 80% smaller file sizes than JPEG/PNG
  • All modern browsers support it since 2020
  • Use the Python script to batch convert entire directories
  • Faster pages = better Core Web Vitals = better rankings

Why WebP?

Google released WebP over a decade ago. It offers up to 80% reduction in image file size with minimal impact on quality.

Since 2020, WebP is supported by all modern browsers. If you're still serving JPEGs and PNGs, you're leaving page speed on the table.

Why this matters for SEO
Faster pages = better Core Web Vitals = better rankings. This is part of the technical SEO checklist that actually matters.

The Problem

Converting images to WebP is a pain. You either:

  • Use slow, resource-heavy plugins that kill your server
  • Waste time on online tools that charge outrageous fees
  • Do it manually, one by one (no thanks)

The Script

This Python script scans your images directory and all subdirectories, converting everything to WebP. Fast.

Python
import os
import PIL
from PIL import Image

MY_DIR = "."  # Your images directory

for root, dirs, files in os.walk(MY_DIR):
    for _this_file in files:
        if _this_file.endswith('.webp'):
            continue
        _source = root + os.sep + _this_file
        try:
            im = Image.open(_source).convert("RGB")
            im.save(_source.rsplit('.', 1)[0] + ".webp", "webp")
        except PIL.UnidentifiedImageError:
            pass

How to Use It

Step 1: Install Pillow

Open your terminal and run:

pip install pillow

Step 2: Run the Script

Save the script as convert_webp.py, update MY_DIR to your images folder path, and run:

python convert_webp.py

Step 3: Done

That's it. All your images are now WebP. Update your HTML/CSS to reference the new .webp files.

Note
The script keeps your original files. Delete them manually after verifying the WebP versions look good.

Want more tactical guides?

Practical SEO frameworks you can implement today.

Get notified