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

Let’s see how to rename image files in a folder to another extension using Python Pillow and glob libraries.
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'))

First, the script accesses every jpg image in the Documents directory.

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

Next, changes the image file extensions from jpg to png (you can modify it since it is working for other extensions as well).

Finally, Python code saves png images in the newly created ImgArchive directory.

File names are iterated from 1. You may want to adjust it to your needs as well.

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

List of 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