Search code examples
pythonsortingasciiglobnumeric

Read file name in numerical order as opposed to ASCI ordering using glob?


I have a list of files named as follows:

file1.png
file2.png
...
file9.png
file10.png
file11.png
...
file99.png
file100.png
file101.png
...

When I read the directories using this code:

images = [file for file in glob.glob(image_dir + '*')]

I get an output which orders the file names as follows:

[image_dir/file1.png
image_dir/file10.png
image_dir/file100.png
image_dir/file101.png
... 
image_dir/file109.png
image_dir/file11.png
image_dir/file110.png
...
image_dir/file119.png
image_dir/file12.png
image_dir/file120.png
...]

How do I get the files in proper numerical order?


Solution

  • Try using:

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