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

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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")]





Not successful it gives the error AttributeError: 'str' object has no attribute 'decode'.
– Ambrish Dhaka
19 hours ago


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.

LgkRmlcAYEh
XLx,dAfG7W9LJRHQ1pYq5jIJqOL0n7Wykpk8cp,fqiuzj,EfgOJtHb6w4s,kKK

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Makefile test if variable is not empty