發表文章

目前顯示的是有「Human Sorting」標籤的文章

常用的 Human Sorting with Python

簡單來說,當 sorting 的結果跟預期的不同,可以試一下。其中奧妙就不多說了,附上原始網址,可以研究一下。 https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import re , os def atoi(text): return int (text) if text . isdigit() else text def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [ atoi(c) for c in re . split( '(\d+)' , text) ] try : dirs = os . listdir(folder) dirs . sort(key = natural_keys) # just in case we need the reverse order #dirs = reversed(dirs) for file in dirs: if not file . endswith( "csv" ): continue csv_path = "%s\\%s" % (folder, file ) print (csv_path) except Exc...