1

I am trying to pick all the images from a folder with an especific name.

The images have the following names:

plotChannel1.png, plotChannel2.png, plotChannel3.png, plotChannel4.png, plotChannel5.png, plotChannel6.png, plotChannel7.png, plotChannel8.png, plotChannel9.png, plotChannel10.png, plotChannel12.png, plotChannel13.png, plotChannel14.png, plotChannel5.png, plotChannel6.png

To pick the images I am using:

dataImage = sort([f for f in os.listdir(os.getcwd()) if f.endswith('.png') and 'Channel' in f]) 

However the result is not as expected, since python is not sorting them in the correct order. It uses the following order:

1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9

How can I force python to sort the images in the correct order?

falsetru
  • 357,413
  • 63
  • 732
  • 636
codeKiller
  • 5,493
  • 17
  • 60
  • 115

1 Answers1

2

sorted or list.sort accepts an additional key function parameter. Pass a function that convert the filename into number, so that sorted sort according to the number, instead of sort it lexicographically.

dataImage = sorted(
    [f for f in os.listdir(os.getcwd()) if f.endswith('.png') and 'Channel' in f]
    key=lambda filename: int(filter(str.isdigit, filename))
)
falsetru
  • 357,413
  • 63
  • 732
  • 636