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?

Dval
  • 83
  • 6
  • 3
    `sorted(os.listdir('path/to/jpg/files'), key=lambda x: int(x.split(".")[0]))` – Rakesh Jul 03 '18 at 12:06
  • 1
    Possible duplicate of [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – khelwood Jul 03 '18 at 12:06

1 Answers1

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])) 
Rakesh
  • 81,458
  • 17
  • 76
  • 113