Reputation: 457
I'm just trying to create a pdf from a list of images in a forder. This is the code:
file_path = input('file path of the images: ')
list = os.listdir(file_path)
pdfimages = [
Image.open(file_path + f)
for f in list
]
print('=== Images used to create the PDF ===\n' +'>>> '+str(list))
pdf_path = file_path + pdf_name + '.pdf'
pdfimages[0].save(
pdf_path, "PDF" , resolution=100.0, save_all=True, append_images=pdfimages[1:]
)
print('=== PDF created and saved! ===')
print('=== Check ===\n' +'>>> '+str(file_path))
The pdf is created, but the order of the photos (checked here: print('=== Images used to create the PDF ===\n' +'>>> '+str(list))
) is not correct, even though it is correct in the folder. Thi is what the code written before shows:
=== Images used to create the PDF ===
>>> ['bho1.jpg', 'bho10.jpg', 'bho11.jpg', 'bho12.jpg', 'bho13.jpg', 'bho14.jpg', 'bho15.jpg', 'bho16.jpg', 'bho17.jpg', 'bho18.jpg', 'bho19.jpg', 'bho2.jpg', 'bho20.jpg', 'bho21.jpg', 'bho22.jpg', 'bho23.jpg', 'bho24.jpg', 'bho25.jpg', 'bho26.jpg', 'bho27.jpg', 'bho28.jpg', 'bho29.jpg', 'bho3.jpg', 'bho30.jpg', 'bho31.jpg', 'bho32.jpg', 'bho33.jpg', 'bho34.jpg', 'bho35.jpg', 'bho36.jpg', 'bho37.jpg', 'bho38.jpg', 'bho39.jpg', 'bho4.jpg', 'bho40.jpg', 'bho41.jpg', 'bho42.jpg', 'bho43.jpg', 'bho44.jpg', 'bho45.jpg', 'bho46.jpg', 'bho47.jpg', 'bho48.jpg', 'bho49.jpg', 'bho5.jpg', 'bho50.jpg', 'bho51.jpg', 'bho52.jpg', 'bho53.jpg', 'bho54.jpg', 'bho55.jpg', 'bho56.jpg', 'bho57.jpg', 'bho58.jpg', 'bho59.jpg', 'bho6.jpg', 'bho60.jpg', 'bho7.jpg', 'bho8.jpg', 'bho9.jpg']
As you can see the pattern isn't bho1.jpg, bho2.jpg, bho3.jpg etc...
, instead it gets firstly the images with the one (bho1.jpg, bho10.jpg, bho11.jpg, bho12.jpg etc...
) than with the two and it goes one like this.
Someone knows why?
Upvotes: 0
Views: 88
Reputation: 150
This is mostly because you are dealing with strings, so they are sorted alphabetically.
I would say to parse the number from each string. You can to this with a simple int(filename[3:-4])
, and sort the filenames using these integer values. In full, you could to this:
file_names = os.listdir(file_path)
file_names = sorted(file_names, key=lambda s: int(s[3:-4]))
You could also use regex to parse the integers, but in your case, you can also do it with indexing ([3:-4]
).
I also took the liberty to rename your list
variable to file_name
, list is a reserved variable in python and shouldn't be changed.
Upvotes: 1