I am trying to get this to create the .jpg without the .png in the file name.
This does convert successfully to .jpg but the filename is mangled.
This line is the problem.
target_name = "sys.argv[1] - 4" + ".jpg"
import os
import sys
from PIL import Image
if len(sys.argv) > 1:
if os.path.exists(sys.argv[1]):
im = Image.open(sys.argv[1])
# Need to backspace 4 times
target_name = "sys.argv[1] - 4" + ".jpg"
# Saved as sys.argv[1] - 4.jpg
rgb_im = im.convert('RGB')
rgb_im.save(target_name)
print("Saved as " + target_name)
else:
print(sys.argv[1] + " not found")
else:
print("Usage: convert2jpg.py <file>")
I've recategorised this under 'applications / programming' as it is NOT related to shell !
- poster - be mindful to categorisation - driving a car is not the same as flying an aeroplane although there is a number of similarities
again, you fail to show input/expected output/actual output./issues faced.
again, ... reflect on posting questions by imagining that (only) you were asked to answer with the information provided, would it be enough to respond without asking for further clarification/information ..... if not then post enough detail for a reasoned to be expected not requests for additional information/clarification.
Try os.path.splitext()
target_name = os.path.splitext(sys.argv[1])[0] + ".jpg"
Thanks MadeInGermany, I will try it.
Hi @cyclist,
I guess your intention was target_name = sys.argv[1][:-4] + ".jpg".
str[:-N] gives the first len(str)-N chars of str, i.e. it strips the last N chars. If N >= len(str), it gives the empty string.
Of course this only works for a 3-char suffix. For a variable length you could use sys.argv[1].rsplit(".", 1)[0] + ".jpg".
I tried it.
File "/home/andy/Python/test.py", line 27
sys.argv[1].rsplit(".", 1)[0] + ".jpg".
^
SyntaxError: invalid syntax
you should not copy-paste the final dot...