function
I would abstract this into a function you can call. Then you can also easily incorporate a few checks to see whether the source path really is a directory, that the destination path actually exists,...
pathlib.Path
Has a lot of convenience methods that help with file path handling.
from PIL import Image
from pathlib import Path
def convert_jpg_to_png(
source: Path,
destination: Path,
overwrite=False,
) -> None:
if not source.is_dir():
raise ValueError(f"{source} is not a directory")
if not source.exists():
raise ValueError(f"{source} does not exist")
if not destination.is_dir():
raise ValueError(f"{destination} is not a directory")
if not destination.exists():
destiny.mkdir(parents=True)
for source_name in source.glob("**/*.jpg"):
# If you want to cover both jpg and jpeg,
# for source_image in source.glob("**/*"):
# if not source_image.suffix.lower in {".jpg", ".jpeg"}:
# continue
destination_name = destination / (
source_name.relative_to(source.with_suffix(".png"))
)
if destination_name.exists() and not overwrite:
print(f"{destination_name} already exists")
continue
print(f"renaming {source_name} to {destination_name}")
with Image.open(source_name) as im:
im.save(destination_name, format="PNG")
The commented bits are if you also want to transform .JPG, .JPEG and .jpeg
main guard
You can then hide your logic behind a if __name__ == "__main__":
guard, so you can later import this module in another program if you want to:
if __name__ == "__main__":
if len(sys.argv) == 1:
source = Path(".") # default: current location
destination = source
overwrite = False
source = Path(sys.argv[1])
if len(sys.argv) > 2:
if sys.argv[2] in {"True", "False"}:
destination = source
overwrite = sys.argv[2] == "True"
else:
destination = Path(sys.argv[2])
else:
destination = source
overwrite = False
if len(sys.argv) > 3:
overwrite = sys.argv[3] == "True"
convert_jpg_to_png(source, destination, overwrite)
Here I manually handled the arguments, but you can better check the argparse
module to simplify this
python test.py foo/img.jpg bar/img.png
, orpython test.py in/ out/
wherein/foo.jpeg
exists. \$\endgroup\$print("Lets go")
once for each file? \$\endgroup\$