Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
How to Batch Resize Images in Python with pathlib and Pillow
Batch resize all JPG images from a source folder and save to a destination folder using pathlib and Pillow.
from pathlib import Path
from PIL import Image
def batch_resize_images(src_dir: str, dest_dir: str, size: tuple[int, int] = (800, 600)) -> None:
src_path = Path(src_dir)
dest_path = Path(dest_dir)
dest_path.mkdir(parents=True, exist_ok=True)
for img_path in src_path.glob("*.jpg"):
if not …
How to Generate Thumbnails While Maintaining Aspect Ratio in Python
Resize images to fit within maximum dimensions while preserving the original aspect ratio using Pillow (PIL).
from PIL import Image
def thumbnail_with_aspect_ratio(image_path, output_path, max_width, max_height):
with Image.open(image_path) as img:
# Get original dimensions
width, height = img.size
# Calculate scaling ratio to fit within max dimensions
ratio = min(max_width / width, max_h…
How to Generate a QR Code in Python
Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.
import qrcode
# Data to encode
data = "https://www.example.com"
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code
img = qr.…
How to Resize Hundreds of Images in Batch with Python
Resize every image in a folder to a target size using Pillow, creating a new subfolder for processed files.
import os
from PIL import Image
def resize_images_in_batch(directory, output_size=(800, 600)):
if not os.path.exists(directory):
print(f"Directory {directory} does not exist.")
return
output_dir = os.path.join(directory, "resized")
os.makedirs(output_dir, exist_ok=True)
for filename in…
How to Strip EXIF Metadata from Images in Python
Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct
def strip_exif(image_bytes, remove_metadata=True):
"""Remove EXIF metadata from image bytes."""
img = Image.open(BytesIO(image_bytes))
if remove_metadata:
# Clear all metadata
img.info.clear()
# Sa…
Browse by section
Each section groups closely related Python snippets.
Automation & scripting — Python code examples
What you will find here
This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.