Search code examples
pythonoperating-systemsortedlist

List ordering with os.listdir - appending files in order


I have a folder of fits files that are all labelled img_1.fits, img_32.fits, img_2.fits ... etc and I want to iterate through them in numerical order and append the data to an array however I cannot seem to sort them. I have tried;

def load_images_sorted(folder):
images = []
for filename in os.listdir(folder):
    file = sorted(os.path.join(folder, filename), key=lambda x: int(os.path.splitext(x.split('_')[1])[0]))
    image_data = fits.getdata(file, ext=0,)
    images.append(image_data)
return np.array(images) 

What can I do to sort them with os? or would glob be more useful?


Solution

  • import re 
    
    def sorted_alphanumeric(data):
        convert = lambda text: int(text) if text.isdigit() else text.lower()
        alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
        return sorted(data, key=alphanum_key)
    
    def load_images_sorted(folder):
        images = []
        for filename in sorted_alphanumeric(os.listdir(folder)):
            # do whatever with these sorted files
            ...