我們在讀取文件夾下面的文件時,有時是希望能夠按照相應的順序來讀取,但是 file_lists=os.listdir()返回的文件名不一定是順序的,也就是說結果是不固定的。就比如讀取下面這些文件,希望能夠按照圖中的順序進行讀取,但是

得到的結果卻是這樣:
['Comprehensive Risk Report_May 10_ 2019 9-00-39 AM 314.html',
'Comprehensive Risk Report_May 11_ 2019 9-00-40 AM 031.html',
'Comprehensive Risk Report_May 12_ 2019 9-00-42 AM 145.html',
'Comprehensive Risk Report_May 13_ 2019 9-00-43 AM 490.html',
'Comprehensive Risk Report_May 14_ 2019 9-00-13 AM 544.html',
'Comprehensive Risk Report_May 15_ 2019 9-00-23 AM 408.html',
'Comprehensive Risk Report_May 16_ 2019 9-00-34 AM 028.html',
'Comprehensive Risk Report_May 17_ 2019 9-00-36 AM 892.html',
'Comprehensive Risk Report_May 1_ 2019 9-00-05 AM 861.html',
'Comprehensive Risk Report_May 2_ 2019 9-00-36 AM 076.html',
'Comprehensive Risk Report_May 3_ 2019 9-00-40 AM 593.html',
'Comprehensive Risk Report_May 4_ 2019 9-00-46 AM 963.html',
'Comprehensive Risk Report_May 5_ 2019 9-00-50 AM 724.html',
'Comprehensive Risk Report_May 6_ 2019 9-00-53 AM 563.html',
'Comprehensive Risk Report_May 7_ 2019 9-00-54 AM 080.html',
'Comprehensive Risk Report_May 8_ 2019 9-00-37 AM 000.html',
'Comprehensive Risk Report_May 9_ 2019 9-00-37 AM 935.html']
而且在采用 file_lists.sort() 以及 sorted(file_lists()) 后,結果還是如此.
這是因為文件排序都是按字符串來的,不會特意給你分成數字,根據文件中字符在ascii碼中的順序,並且將字符串中每個字符作比較,得到結果。上面的 11和1_的問題,1相同,而后一位1在_前面,如果換成減號-那它就在1前面,或者將序號放在最后,那排序就正常了,這就是按中間字符排序會出現亂七八糟問題的原因
這時就需要自己根據文件自定義排序:
# 讀取文件並進行排序
filelists = os.listdir(path)
sort_num_first = []
for file in filelists:
sort_num_first.append(int(file.split("_")[1].split(" ")[1])) # 根據 _ 分割,然后根據空格分割,轉化為數字類型
sort_num_first.sort()
print(sort_num_first)
sorted_file = []
for sort_num in sort_num_first:
for file in filelists:
if str(sort_num) == file.split("_")[1].split(" ")[1]:
sorted_file .append(file)
思路很簡單,就是把文件名根據 _ 和 空格 分割,得到中間的數字,然后進行排序;然后將排好的數字一一對應到相應的文件名,就得到了排好了的文件。
