我正在使用python 2.7
而我正在尝试读取文件夹中的文件名,并按照令人憎恶的顺序排序。
我的代码是:
filenamelist=[]
txt_path = 'decoded'
for filename in sorted(os.listdir(txt_path)):
with open(txt_path+"/"+filename) as myfile:
for line in myfile:
if "Total Time" in line:
filenamelist.append(filename)
当我打印filenamelist
时,我得到以下内容:
[' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_ level_0 _192x144_15_50_dec.txt',' p irkagia_10b_lowdelay_P_192x144_Filters_OFF_的 level_10 _192x144_25_42_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_的 level_11 _192x144_25_38_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_12_192x144_25_34_dec.txt',&#39 ; pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_13_192x144_25_30_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_14_192x144_25_26_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_15_192x144_25_22_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_1_192x144_15_46_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_2_192x144_15_42_dec.txt&#39 ;,' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_3_192x144_15_38_dec.txt',' pirkagia_10b_lowdelay_P_192x144_Filters_OFF_level_4_192x144_15_34_dec.txt',...]
可以看出,这没有排序。我想获得level_0, level_1, level_2, ..., level_9, level_10...]
。
你能帮我吗?
答案 0 :(得分:0)
感谢@bakaDev
这是我问题的解决方案:
import re #for natural sorting
filenamelist=[]
txt_path = 'decoded'
_nsre = re.compile('([0-9]+)')
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower()
for text in re.split(_nsre, s)]
fnlist = os.listdir(txt_path)
fnlist.sort(key=natural_sort_key)
for filename in fnlist):
with open(txt_path+"/"+filename) as myfile:
for line in myfile:
if "Total Time" in line:
filenamelist.append(filename)