Search code examples
pythonpython-os

How to sort an int from a file


I have this code:

import glob
import os

for file in glob.glob("./data/*.jpg"):
    lel=(os.path.basename(file))
    lel = (os.path.splitext(lel)[0])
    list1 = lel
    list1 = [int(x) for x in list1]
    list1.sort()
    print(list1)

and it gives this output:

[0]
[1]
[0, 1]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]
[2]
[0, 2]
[1, 2]
[2, 2]
[2, 3]
[2, 4]
[2, 5]
[2, 6]
[2, 7]
[2, 8]
[2, 9]
[3]
[0, 3]
[1, 3]
[2, 3]
[3, 3]
[3, 4]
[4]
[5]
[6]
[7]
[8]
[9]

is there a way to make it output this?:

0
1
2
3
4
5
6
7
8
9
10
etc etc..

Solution

  • From what I can tell, you have files named 0.jpg, up to 34.jpg

    You need to remove [int(x) for x in list1] because this gets a list per file

    If you want to sort the numbers in ascending order rather than lexicographic, then make a list outside the loop, e.g.

    import glob
    import os
    
    files = []
    for file in glob.glob("./data/*.jpg"):
        lel = os.path.basename(file)
        lel = os.path.splitext(lel)[0]
        files.append(int(lel))
    files.sort()
    for f in files:
        print(f)