0

So I've been trying to sort list files but have been unsuccessful in doing so. My folders have filed such as 0.jpg,1.jpg,... and I want to sort the files into ascending order but have been unsuccessful in doing so. Here is my code.

a=os.listdir(path)
sorted(a)
for i,j in enumerate(a):
    print(i,j)

but this gives me 0 .DS_Store

1 0.jpg
2 1.jpg
3 10.jpg
4 1000.jpg
5 1001.jpg
6 1002.jpg
7 1003.jpg
8 1004.jpg
9 1005.jpg
10 1006.jpg
11 1007.jpg
12 1008.jpg
13 1009.jpg
14 101.jpg
15 1010.jpg
16 1011.jpg
17 1012.jpg
robotlover
  • 331
  • 1
  • 2
  • 12
  • 1
    `sorted(a)` returns a new list, `a` is unchanged. Either use `a.sort()` or `a = sorted(a)`. – Martijn Pieters Sep 30 '18 at 12:45
  • 1
    `a.sort(key = lambda x: int(x.split('.')[0]))` Do like this. – Rohit-Pandey Sep 30 '18 at 12:46
  • Next, you have *text*, not numbers. `'2'` sorts after `'1234'` because the `2` character comes after the `'1'` character in the characterset, just like `'b'` comes after `'a'`. You'd want to convert the portion before the extension to integers for sorting. – Martijn Pieters Sep 30 '18 at 12:46

0 Answers0