python 按照自然数排序遍历文件 python os.listdir sort by natural sorting
import os import re def sorted_aphanumeric(data): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(data, key=alphanum_key) file = sorted_aphanumeric(os.listdir("./2")) for f in file: print(f)
参考
https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir
Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:
import re
def sorted_aphanumeric(data):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(data, key=alphanum_key)
You can now use this function to sort a list:
dirlist = sorted_aphanumeric(os.listdir(...))