I'm attending an online course about python3.
I'M trying to solve the following problem:
By other words, I need to grab folder1 , from where the JPEG images are loaded, then we convert those images into PNG format and save them to folder2.Write a script that takes 2 arguments from the command lines. Those 2 arguments are 2 folder paths in which a few images will be loaded and saved after being converted from 'jpeg' to 'png'.
I want to use module Pathlib and PIL to solve this problem.
I have this code made by me but I'm not happy with it at all because I feel I'm running round and round to get to the final goal and I'm sure there's a way more logic way of doing this.
Code: Select all
import sys
from pathlib import Path
from PIL import Image
# grab first and second argument
# check if new/ exists, if not, create it
# loop through the folder and convert to png
# save to the new folder
def proc_args():
"""Process arguments from command line"""
if len(sys.argv) < 3:
print('Not enough parameters!')
exit(-1)
else:
newpath = Path(sys.argv[2])
try:
newpath.mkdir(parents=True, exist_ok=False)
except FileExistsError:
print(f'{newpath} already exists!')
except IOError as ioerr:
print(f'{ioerr}: {newpath} could not be created')
return newpath
def conv_imgs(pold_p, pnew_p):
"""Loop over files in folder"""
for item in Path(pold_p).rglob('*.jpg'):
img = Image.open(item)
noext = item.with_suffix('')
newext = noext.with_suffix('.png.png')
tmp = Path(newext).stem
print(tmp)
img.save(Path(pnew_p).joinpath(tmp), 'png')
def main():
"""Main Function"""
old_path = Path(sys.argv[1])
new_path = proc_args()
conv_imgs(old_path, new_path)
if __name__ == '__main__':
main()