-4

I am trying to convert all my images in a file into jpg format, defined as 'a' but I keep getting error as cannot convert. Any help?

   from PIL import Image
import matplotlib.pyplot as plt
import os
#import imtools
#path = imtools.get_imlist('.')
a = 'K:\wq'
for infile in os.listdir(a):
    outfile = os.path.splitext(infile)[0] + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except OSError as error:
            print ("cannot convert", infile)

error log: cannot convert manojcasual.png

Process finished with exit code 0

Manoj
  • 69
  • 1
  • 8
  • Can you post your full error? – Rakesh Feb 23 '18 at 11:59
  • Please paste error log – gonczor Feb 23 '18 at 11:59
  • Possible duplicate of [os.path.isdir() returns False even when folder exists](https://stackoverflow.com/questions/18299949/os-path-isdir-returns-false-even-when-folder-exists) – Jongware Feb 23 '18 at 12:01
  • Possible Solution : https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python – JamesBond Feb 23 '18 at 12:01
  • C:\Users\manoj\venv\triedmanytimes\Scripts\python.exe C:/Users/manoj/PycharmProjects/triedmanytimes/Changingformat.py cannot convert manojcasual.png Process finished with exit code 0 – Manoj Feb 23 '18 at 12:01
  • Catch the error with `except OSError as error:`. Print the error, and edit the question – Peter Wood Feb 23 '18 at 12:05

1 Answers1

-1

os.listdir() returns the name of the files, without the path.

Unless the files are in your current working directory, you must give the complete path to open them. You can use os.path.join() for that.

Also, note that some sequences like '\n' are parsed as special characters in ordinary strings. This can be a problem on Windows, if any of the escape sequences appears in the path, as in 'C:\new'. To avoid problems, you should always write your literal paths as raw strings (r'.....') to tell Python not to interpret these sequences.

So, your code should look like:

from PIL import Image
import matplotlib.pyplot as plt
import os

a = r'K:\wq'  # notice the r'...'

for infile in os.listdir(a):
    outfile = os.path.splitext(infile)[0] + ".jpg"
    if infile != outfile:
        try:
            Image.open(os.path.join(a, infile)).save(os.path.join(a, outfile))
        except OSError as error:
            print ("cannot convert", infile)
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50