Python sort files by filename with numbers as first letters
Question:
I have the following list which is the output of mylist.sort()
['0_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav', '5_sound.wav']
This makes sense, since the filenames are treated as strings. But I want the following order:
['0_sound.wav', '5_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav']
What is a good way of archieving this? The filename may vary, it´s not always "sound", which would make it easier.
Answers:
Assuming that there will always be an underscore _
as a separator:
files = ['0_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav', '5_sound.wav']
files.sort(key=lambda x: int(x.split('_')[0]))
Result:
['0_sound.wav', '5_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav']
Note: This will fail if there are unexpected filenames that don’t have this separator or that don’t start with a number, if that is even possible I would suggest filtering that list first so you don’t get unexpected errors
I have the following list which is the output of mylist.sort()
['0_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav', '5_sound.wav']
This makes sense, since the filenames are treated as strings. But I want the following order:
['0_sound.wav', '5_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav']
What is a good way of archieving this? The filename may vary, it´s not always "sound", which would make it easier.
Assuming that there will always be an underscore _
as a separator:
files = ['0_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav', '5_sound.wav']
files.sort(key=lambda x: int(x.split('_')[0]))
Result:
['0_sound.wav', '5_sound.wav', '10_sound.wav', '15_sound.wav', '20_sound.wav']
Note: This will fail if there are unexpected filenames that don’t have this separator or that don’t start with a number, if that is even possible I would suggest filtering that list first so you don’t get unexpected errors