0

I have a list of files from a directory and I apply sort to order them as in

the_list=os.listdir(dir_name)
img_list = [i for i in the_list if i.endswith('.png') ]
img_list.sort()

My problem is that the files are like this:

file_0.png  file_1.png file_2.png ....file_10.png file_11.png ...etc

as a result, my algorithm orders them incorrectly as

'file_0.png', 'file_1.png', 'file_10.png', 'file_100.png', 'file_1000.png', 'file_1001.png', 'file_1002.png', 'file_1003.png', 'file_1004.png',...

How can I order them corretly so that file_2.png comes after file_1.png?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

1 Answers1

0

It could be achieved as

img_list.sort(key=lambda name: int(re.match('[^\d]*(\d+).*', name)[1]))
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sighingnow
  • 791
  • 5
  • 11