-1

I need to sort images based on numbers in the file Name.

For example: [1.jpg, 10.jpg, 3.jpg... ]

I tired natsort library and sorted function the both give the same result

import glob 
from natsort import natsorted
images =[]
for img in glob.glob('E:/train/image/*.jpg'):
    images.append(img)
    natsorted(images)

it Outputs: [1, 10, 11, 12, 2, 22, 3]

but it must be: [1, 2, 3, 10, 11, 12, 22]

Nima Mousavi
  • 1,601
  • 2
  • 21
  • 30
K.Taima
  • 1
  • 1
  • 3
    You've asked for a naturally-sorted copy of the contents of `images`, and then thrown it in the trash. – user2357112 Apr 03 '19 at 04:27
  • How about accepting and upvoting the best answer. – Nima Mousavi Apr 03 '19 at 11:04
  • Possible duplicate of [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – Nima Mousavi Apr 03 '19 at 11:08

2 Answers2

0

I guess you need to do the following:

import glob 
from natsort import natsorted
images = natsorted(glob.glob('E:/train/image/*.jpg'))
Jeril
  • 7,858
  • 3
  • 52
  • 69
0

natsorted is not an in-place sort. It returns a new sorted list so you must assign it to a variable.
This should work:

import glob 
from natsort import natsorted
images =[]
for img in glob.glob('E:/train/image/*.jpg'):
    images.append(img)
images = natsorted(images)
hsnsd
  • 1,728
  • 12
  • 30