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:
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)