Search code examples
pythonpython-3.xsortedlist

How to sort numeric file names?


There is a folder with some images(slices) in it that they are sorted. A sample of the file names that are sorted in the folder is:

  0.7.dcm
 -1.1.dcm
  2.5.dcm
 -2.9.dcm
 -4.7.dcm
 -6.5.dcm
 -8.3.dcm
 -10.1.dcm

and some of them are as:

 -10.000000.dcm
 -12.500000.dcm
 -15.000000.dcm
 -17.500000.dcm
 -20.000000.dcm
 -22.500000.dcm
 -25.000000.dcm
 -27.500000.dcm

But when I want to read them, they load as an unsorted list. I tried some methods but the problem isn't solved yet:

for person in range(0, len(dirs1)):
    for root, dirs, files in os.walk(os.path.join(path, dirs1[person])):
        dcmfiles = [_ for _ in files if _.endswith('.dcm')]  # ['-10.000000.dcm', '-22.500000.dcm', '-17.500000.dcm', '-27.500000.dcm', '-25.000000.dcm', '-12.500000.dcm', '-20.000000.dcm', '-15.000000.dcm']
        dcmfilesList = sorted(dcmfiles, key = lambda x: x[:-4]) # ['-10.000000.dcm', '-22.500000.dcm', '-17.500000.dcm', '-27.500000.dcm', '-25.000000.dcm', '-12.500000.dcm', '-20.000000.dcm', '-15.000000.dcm']

and also I checked Sort filenames1, Sort filenames2, Sort filenames3.

How can I read .dcm slices as sorted in python3 such as below?

['0.7.dcm', '-1.1.dcm', '2.5.dcm', '-2.9.dcm', '-4.7.dcm', '-6.5.dcm', -8.3.dcm', '-10.1.dcm'].

and

 ['-10.000000.dcm', '-12.500000.dcm', '-15.000000.dcm', '-17.500000.dcm', '-20.000000.dcm', '-22.500000.dcm', '-25.000000.dcm',  '-27.500000.dcm'].

Solution

  • you are not converting them to numbers before sorting, so it's not working.

    import os
    
    for root, dirs, files in os.walk('./'):
            dcmfiles = [_ for _ in files if _.endswith('.dcm')]
            dcmFilesList = sorted(dcmfiles, key=lambda x: float(x[:-4]))
    

    To sort ignoring sign, lambda x: abs(float(x[:-4]))