How to rename image files in a folder all to another extension?

Learn how to batch rename and convert image files to different extensions using Python’s Pillow and glob libraries for bulk image processing.

image extension python change

Changing extensions

The script works for changing the extension from jpg to png, png to jpg, and any other.

You may also just change the name or make other modifications after minor changes in the script.

from PIL import Image
import glob

for (i, filename) in enumerate(glob.glob("C:/Users/pythoneo/Documents/*.jpg")):
    print(filename)
    img = Image.open(filename)
    img.save('{}{}{}'.format('C:/Users/pythoneo/Documents/ImgArchive/', i+1, '.png'))

Use glob.glob() to recursively find all JPG files matching a pattern in your Documents directory.

See also  How to Build Custom Image Processing Filters with Advanced Algorithms

Open each image with Image.open() and save with a new extension using Image.save(), which automatically handles format conversion.

The img.save() function writes converted images to a destination directory with new filenames and extensions.

File enumeration starts at 0; add 1 to create filenames starting from 1, or modify the enumeration logic to use original filenames instead.

See also  How to rotate image around custom point in Pillow?

Console Output: Processing Multiple Image Files

In the console, there is a list of modified files printed out.

C:/Users/PycharmProjects/myProject/venv/Scripts/python.exe
C:/Users/pythoneo/PycharmProjects/myProject/file.py
C:/Users/pythoneo/Documents/meme.JPG
C:/Users/pythoneo/Documents/image.jpg
C:/Users/pythoneo/Documents/family foto.JPG
C:/Users/pythoneo/Documents/numpy code.JPG
C:/Users/pythoneo/Documents/pillow python tutorial.JPG

Process finished with exit code 0