problem of merging images to PDF from other directory
#69
Closed
opened 3 years ago by josch
·
0 comments
Loading…
Reference in New Issue
There is no content yet.
Delete Branch '%!s(<nil>)'
Deleting a branch is permanent. It CANNOT be undone. Continue?
By fung on 2020-03-16T13:27:24.198Z
I am working to merge .jpg images to a single PDF file. All images are stored in a folder and ended with ".jpg". The number of images will be different at different times. I do know how many images would be in the folder in each time. And my images are all named "0.jpg", "1.jpg", "2.jpg"...
I did find a code on the internet to do this job :
import os
import img2pdf
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir('.') if i.endswith(".jpg")]))
But this code retracted the input images should be in the same directory with the program file.
To be more organized, I want to separate them, that the images would be in a different directory.
I tried:
import os
import img2pdf
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir('the path of my input images') if i.endswith(".jpg")]))
Then, I got
How can I solve this problem? Or is there an alternative solution to my problem? Thank you.
By josch on 2020-03-16T14:20:02.538Z
This is not an img2pdf problem. This is a Python programming problem. Since there were many people before you who did also not know how to list files inside a directory, I will add some example code to the readme...
By josch on 2020-03-16T14:32:41.320Z
Btw, this contains the answer to your question: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
By josch on 2020-03-16T15:07:42.352Z
In commit
5375a17181
I now added more examples to the README. Do these solve your problem?By fung on 2020-03-16T15:56:58.794Z
Thank you for your swift reply.
I am able to fix this by adding os.chdir('path') to changes the working directory and add sorted() in front of os.listdir('.') to make the files in order.
By fung on 2020-03-16T15:56:59.292Z
Status changed to closed
By josch on 2020-03-16T22:58:27.941Z
Sure, adding an
os.chdir()
will fix your issue but it is not the proper solution. Please consider the solutions presented in the stackoverflow link I posted or the ones I now listed in the README. Specifically you need to do os.path.join(dirname, filename) to get the right full path to each of your files. Using os.chdir() might work now but is prone to introducing new funny bugs into your software...