Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort files in python in numeric order?

Tags:

python

sorting

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?

like image 619
Dval Avatar asked Jul 03 '18 12:07

Dval


1 Answers

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])) 
like image 193
Rakesh Avatar answered Sep 28 '22 09:09

Rakesh