1

I have this code to import images from a folder but the images come in the this order:

test1.png
test10.png
test100.png
test101.png
test102.png
test103.png
test104.png
test105.png
test106.png
test107.png
test108.png
test109.png
test11.png
test110.png
test111.png
test112.png
test113.png
test114.png
test115.png
test116.png
test117.png
test118.png
test119.png
test12.png
etc...

The order that I want is test1, test2, test3, etc...

How can I achieve that?

test_set = []
test_result=[]
test_dir= "C:/Users/anwer/Desktop/copy/test/"

for file in os.listdir(test_dir):
    test_set.append((give_peak_sum(test_dir+file), file))
    test_result.append((give_peak_sum(test_dir+file)))
    print(file)
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

2

Your need to sort the list first.

If all your file starts with 'test'

you can using

yourlist.sort(key=lambda x: int(x.split('.')[0][4:]))
Heaven
  • 491
  • 3
  • 11
1

Sort by the integer in the filename:

import os

def key(filename):
    return int(os.path.splitext(filename)[0][4:])

files = os.listdir(test_dir)
sorted_filenames = sorted([filename for filename in files], key=key)
gmds
  • 19,325
  • 4
  • 32
  • 58