0

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 print the list after sorting.

import os
import glob

images_path = os.path.expanduser('~\\Desktop\\samples\\')

def img_path_list():
    img_list = []
    for file_path in glob.glob(str(images_path) + "*.jpg"):
        img_list.append(file_path)

    img_list.sort(key=lambda x: str(x.split('.')[0]))

    return img_list

print(img_path_list())

The result it's still i.e: [Desktop\\t0.jpg, Desktop\\t1.jpg, Desktop\\t10.jpg, Desktop\\t11.jpg, Desktop\\t2.jpg, ...]

EDIT: not a duplicate as long as I didn't request to use natsort module but with simple python.

lucians
  • 2,239
  • 5
  • 36
  • 64
  • The result looks very sorted to me. You want to have t2.jpg before t10.jpg? – Rickyy Jun 16 '18 at 20:45
  • The result is an example. Yes, normal sorting. 123 instead of 1, 10, 2, 20, etc.. – lucians Jun 16 '18 at 20:46
  • `EDIT: ...` sorry but your restrictions aren't our concern. – cs95 Jun 16 '18 at 21:21
  • Understand that you're looking to naturally sort on something. Whether you asked for an external module or not, that question has been asked before. So it is a duplicate, regardless of whether this is your homework or not. – cs95 Jun 16 '18 at 21:27

1 Answers1

3

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.
jpp
  • 159,742
  • 34
  • 281
  • 339