1

I am making a program that shows pictures that were downloaded automatically by said program. I have it so the program makes a list of all the pictures as PIL.Image objects. The pictures are saved as jpegs and they are named numerically (1.jpg,2.jpg,3.jpg,4.jpg,5.jpg.....). The problem I am having is that when I try to make said list I need to get all the paths to all the images to make the PIL.Image objects. I used os.listdir(path) and it worked great until I realised that it did not "sort" the images numerical. That means that it went like this: [1.jpg,10.jpg,100.jpg,101.jpg......2.jpg,20.jpg....] I need a way to sort this list so it outputs: [1.jpg,2.jpg,3.jpg.....] I can't sort like I would integers because they are strings with the ".jpg" at the end. A simplified version of my problem:

for i in os.listdir(path):
    ...
output: ["1.jpg","10.jpg","100.jpg", ...]

I want something to output: ["1.jpg","2.jpg","3.jpg",....]
Nick Diam
  • 31
  • 3

2 Answers2

3

You can do :

nums = sorted([ int(num.split('.')[0]) for num in output]) #split the names and sort numbers
final_output = [ str(i)+".jpg" for i in nums] #append file extension and create another list.

One liner :

final_output = [ str(i)+".jpg" for i in sorted([ int(num.split('.')[0]) for num in output])]

Note: While this may not be optimal, but gets the thing done.

ABcDexter
  • 2,751
  • 4
  • 28
  • 40
2

You can sort the output of listdir based on names in the following way,

import os
for i in sorted(os.listdir(".."), key=lambda x: int(x.split(".")[0])):
    print(i)

Here the os.listdir output is split by '.' and then converted it to int before sorting them.

Himaprasoon
  • 2,609
  • 3
  • 25
  • 46