Converting JPG images to PNG I had a task to convert some JPG images into PNG format using Python. I successfully did it but I was wondering if somehow I could make my code better than my current one.

Code - 

#Python Code

import os  
from PIL import Image  

path1 = sys.argv[1]  
path2 = sys.argv[2]  

if not os.path.exists(path2):
    os.makedirs(path2)  

for filename in os.listdir(path1):
    if filename.endswith(".jpg"):
        # print(filename.split(".")[0])
        im = Image.open(f"{path1}{filename}")
        # print(Image.open(f"{path1}{filename}"))
        im.save(f"{path2}/{filename.split('.')[0]}.png", "png")
        print("Lets go")
Not much to improve upon, just some minor housekeeping.



Help the end user!

If I was using this script, and forgot to put one or both of the filepaths when calling the script, there would be this error: IndexError: list index out of range. This error wouldn't help the user in a significant way. Consider this:

try:
    path1 = sys.argv[1]  
    path2 = sys.argv[2]
except IndexError:
    raise Exception("Usage: python3 jpg_to_png.py &lt;path to input folder&gt; &lt;path to output folder&gt;")


This gives the user a detailed message on how the use your script.

Remove commented code.

Code you don't need anymore adds useless clutter, and can make your code harder to read.