Skip to content Skip to sidebar Skip to footer

Sort List Of Paths By File Basename (python)

I have a folder with images. I added to a list the paths for each image. They are not alphabetically sorted. I made this function to sort but I the result it's the same when I prin

Solution 1:

Using os.path.basename and assuming your filenames are all of the format X#.jpg with X a single character:

import os

img_list = ['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
            'Desktop\\t10.jpg', 'Desktop\\t11.jpg',
            'Desktop\\t2.jpg']

img_list.sort(key=lambda x: int(os.path.basename(x).split('.')[0][1:]))

print(img_list)

['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
 'Desktop\\t2.jpg', 'Desktop\\t10.jpg',
 'Desktop\\t11.jpg']

With a named function to illustrate how lambda works:

def sorter(x):
    return int(os.path.basename(x).split('.')[0][1:])

img_list.sort(key=sorter)

Explanation

There are a few steps here:

  1. Extract the filename via os.path.basename.
  2. Split by . and extract first element.
  3. Then slice by 1st character onwards.
  4. Convert the result to int for numerical ordering.

Post a Comment for "Sort List Of Paths By File Basename (python)"