ImportOSImportRedefsorted_aphanumeric (data): Convert=LambdaText:int (text)ifText.isdigit ()Elsetext.lower () Alphanum_key=LambdaKey: [Convert (c) forCinchRe.split ('([0-9]+)', Key)] returnSorted (data, key=alphanum_key) file= Sorted_aphanumeric (Os.listdir ("./2")) forFinchFile:Print(f)
Reference
Https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir
Python for whatever reason does no come with a built-in a-to has natural sorting (meaning 1, 2, instead of 1, ten, 2), so you had to write it yourself:
ImportReDefSorted_aphanumeric(Data):Convert= LambdaText:Int(Text) IfText.IsDigit() ElseText.Lower() Alphanum_key = lambda Key: [ Convert (c for C in Re. ( ([0-9]+) ' , Key ) ] return Sorted (data, Key= alphanum_key)
You can now use the This function to sort a list:
dirlist = sorted_aphanumeric(os.listdir(...))
Python traverses files by natural number Python Os.listdir sort by natural sorting