Search code examples
pythonsortingglob

Python glob: sorting files of format [int]_[int] the same as windows name sort


I have files that are sorted by name in windows like the following:

1_0
1_1
1_2
1_3
1_4
1_5
1_6
1_7
1_8
1_9
1_10
1_11
2_0
2_1

Per above the first integer before the _ should be the first sort, followed by the integer after the _. I want to sort in glob the same way. However, when I use sorted(glob.glob(files)) I get an order like the following instead:

1_1
1_10
1_11
1_12
1_13
1_14
1_15
1_16
1_17
1_18
1_19
1_2

For files of the above format, is there a simple way to make glob sort by name the same way as windows does?


Solution

  • You can give multiple keys to the sorting function in order of relevance

    sorted(glob.glob(files), key=lambda x: (int(x.split('_')[0]), int(x.split('_')[1])))
    

    ['1_0', '1_1', '1_2', '1_3', '1_4', '1_5', '1_6', '1_7', '1_8', '1_9', '1_10', '1_11', '2_0', '2_1']