0

I got a lot of images/files in folder. They looks like

result-01  -> result-176 

When I make a video from images I got wrong order (after result-10.png goes result-100.png instead of result-11.png). How to sort my files?

os.listdir(path).sort() dont works

for filename in os.listdir(path):
    print(filename)

I want to get

result-01.png
result-02.png
...
result-08.png
result-09.png
result-10.png
result-11.png
result-12.png

instead of

result-01.png
result-02.png
...
result-08.png
result-09.png
result-10.png
result-100.png
result-101.png
result-102.png
Andrei Belousov
  • 581
  • 5
  • 12
  • 1
    `list.sort` sorts strings. You need a function to parse the file number from its name and then you can do `.sort(key=file_number)` – Reut Sharabani Oct 28 '19 at 14:46

3 Answers3

1

try this:

names = ['result-01.png', 'result-100.png', 'result-12.png']

sorted(names, key=lambda x:int(x.split('-')[-1].split('.')[0]))

output:

['result-01.png', 'result-12.png', 'result-100.png']
Dan
  • 1,575
  • 1
  • 11
  • 17
1

list.sort sorts strings as strings.

You need a function to parse the file number as an integer from the file name and then you can do sort(key=parse_file_number)

def parse_file_number(f):
    return int(f[len('result-'):-len('.png')])

And now you can do:

for filename os.listdir(path).sort(key=parse_file_number):
    # do something with filename
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
0

Have you tried using the sorted function?

import os

for filename in sorted(os.listdir("C:\\")):
    print(filename)

Sam
  • 533
  • 3
  • 12
  • sort and sorted dont help The tips above solved the problem – Andrei Belousov Oct 29 '19 at 07:43
  • Sort/Sorted are still used in the above solutions, however it sorts via a-z and not on the file number. So in the solutions above, they use 'sort' to sort the values based on the split filename (number) and not the filename as a whole. – Sam Oct 29 '19 at 09:26