Try:
from PIL import Image
img = Image.open(filename)
print(img.format) # 'JPEG'
More info
-
https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.format
-
https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html