5

I'm creating pdf file from images but having problem with sorting the jpg files in numeric order I have 20 files from 1.jpg to 20.jpg I'm using below code to sort all files in order

import os
sorted(os.listdir('path/to/jpg/files'))

but it will print 1.jpg, 11.jpg, 12.jpg and so on.

Any ideas?

2

1 Answer 1

5

sorted takes a key. You can use lambda function in the key to do a numeric order sort.

Ex:

import os
sorted(os.listdir('path/to/jpg/files'), key=lambda x: int(x.split(".")[0])) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.