pythonimagepython-imaging-libraryimage-conversion

Running image conversion script gives me "no such file"


I have this image conversion script written in Python. I have some images in a folder that go like turbo1, turbo2, and so on...

I need to convert them from png to jpeg.

This is my code:

from PIL import Image
import os

directory = r'C:\Users\Filip\Desktop\turbos'
c=1
for filename in os.listdir(directory):
    if filename.endswith(".PNG"):
        im = Image.open(filename)
        name='turbo'+str(c)+'.jpeg'
        rgb_im = im.convert('RGB')
        rgb_im.save(name)
        c+=1
        print(os.path.join(directory, filename))
        continue
    else:
        continue

I get this error:

Traceback (most recent call last):
  File "c:\Users\Filip\Desktop\convert.py", line 9, in <module>
    im = Image.open(filename)
  File "C:\Python\lib\site-packages\PIL\Image.py", line 2953, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'turbo1.PNG'

If I change filename.endswith(".PNG"): to filename.endswith(".png"): it does not give me that error but the images don't convert.

What am I missing here?


Solution

  • .png and .PNG. are two different file extensions and your code should be

    im = Image.open(os.path.join(directory, filename))