Selecting the folder for performing specific operation on JPG files in tkinter

Multi tool use


Selecting the folder for performing specific operation on JPG files in tkinter
I have written a function for tkinter GUI in python as below:
def mgpd():
answer = filedialog.askdirectory(parent=root,
initialdir=os.getcwd(),
title="Please select a folder:")
if len(answer) > 2:
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir(answer) if i.endswith(".jpg")]))
else:
pass
t2.delete(0, 'end')
t2.insert('insert', 'task completed.')
Now when I select a folder the type error is given as TypeError: a bytes-like object is required, not 'str'
. The problem is around endswith
I guess.
TypeError: a bytes-like object is required, not 'str'
endswith
2 Answers
2
Python complaining about bytes-like objects is usually because whatever string you're trying to alter is encoded. Instead of if i.endswith(".jpg")]
, try if i.decode().endswith(".jpg")]
.
if i.endswith(".jpg")]
if i.decode().endswith(".jpg")]
AttributeError: 'str' object has no attribute 'decode'
I can't exactly simulate your code so it's harder to get an exact answer, however
i.endswith(b'.jpg')
or from binascii import dehexlify
and unhexlify(i).endswith(".jpg")]
could work.– tira
19 hours ago
i.endswith(b'.jpg')
from binascii import dehexlify
unhexlify(i).endswith(".jpg")]
maybe that is adding more a complexity, all I just want is to read all jpg files and pack it into a pdf. If the above code could be simplified or an alternative given is welcome.
– Ambrish Dhaka
12 hours ago
Finally this is the answer:
def mgpd():
image_files =
answer = filedialog.askdirectory(parent=root,
initialdir=os.getcwd(),
title="Please select a folder:")
if len(answer) > 2:
for file in os.listdir(answer):
if file.endswith(".jpg"):
image_files.append(os.path.join(answer, file))
else:
pass
outfile = os.path.join(answer, 'output.pdf')
pdf_bytes = img2pdf.convert(image_files)
file = open(outfile, "wb")
file.write(pdf_bytes)
t2.delete(0, 'end')
t2.insert('insert', 'task completed.')
Can this code be further simplified, welcome.
– Ambrish Dhaka
2 hours ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not successful it gives the error
AttributeError: 'str' object has no attribute 'decode'
.– Ambrish Dhaka
19 hours ago