1

I am generating a list of files in a directory and I want them to be sorted according to numerical value in the filename.

Files:

0.png
1.png
2.png
...
11.png
12.png

and so on

If I generate the list using os.listdir() and then invoke the .sort() method on the list, it looks like shown below:

['0.png', '1.png', '10.png', '11.png', '12.png', '13.png', '14.png', '15.png', '16.png', '17.png', '18.png', '19.png', '2.png', '20.png', '21.png', '22.png', '23.png', '24.png', '25.png', '26.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png', '9.png']

How can I sort it according to numerical value of the name?

On Windows OS, in the Windows Explorer if I sort by the column name in the Details view, it sorts the way I want it to. Can this be done with Python as well?

Thanks.

Neon Flash
  • 3,113
  • 12
  • 58
  • 96

1 Answers1

3

You can use the builtin sorted function and supply a key.

Below the key is a function that converts the first part of the filename (before the '.') to an integer. The sort order uses the results of those function calls but actually sorts the original objects.

l = ['0.png', '1.png', '10.png', '11.png', '12.png', '13.png', '14.png', '15.png', '16.png', '17.png', '18.png', '19.png', '2.png', '20.png', '21.png', '22.png', '23.png', '24.png', '25.png', '26.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png', '9.png']

sorted(l, key=lambda fname: int(fname.split('.')[0]))

returns

['0.png', '1.png', '2.png', ..., '26.png']
Alex
  • 18,484
  • 8
  • 60
  • 80