Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort OS Listdir With Numbers in String

I have a folder. In this folder are files that look sort of like this:

'page_121.png', 'page_122_png', 'page_123.png'... etc

When running this bit of code in Python:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sorted(os.listdir())

Something like this is returned:

'page_276.png', 'page_277.png', 'page_278.png', 'page_279.png', 'page_28.png', 'page_280.png', 'page_281.png', 'page_282.png'

Notice how it sorts them alphanumerically, but going from 279, it jumps to 28, which makes sense, but is not my desired result. How might I get it so that the array returned is in the order of the numbers smallest to largest, so that page_28.png is over in between page_27.png and page_29.png?

>Solution :

You’re sorting strings which, by default, is done in alphabetical order. Therefore, "279" is going to come before "28". What you want to do is sort the strings by integer contained within the string. To accomplish this, you can do the following.

def extract_integer(filename):
    return int(filename.split('.')[0].split('_')[1])

sorted(os.listdir(), key=extract_integer)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading