python對目錄下的檔案進行 多條件排序

2022-08-31 17:12:18 字數 3019 閱讀 2567

在進入正題之前,先介紹一下基礎知識:

1、sort(),方法:就是對列表內容進行正向排序,直接在原列表進行修改,返回的是修改後的列表

lists =[1, 5, 10, 8, 6]

lists.sort()

print

(lists)

>>> [1, 5, 6, 8, 10]

2、sorted() 方法: 對列表進行排序後,返回乙個新的列表,而原列表不變。並且sorted()方法可以用在任何資料型別的序列中,而返回的總是乙個列表的形式。

lists = [1, 5, 10, 8, 6]

a =sorted(lists)

print

(lists)

>>>[1, 5, 10, 8, 6]

print

(a)>>>[1, 5, 6, 8, 10]

3、進行多條件排序,使用引數 key 即可,其返回的順序就是按照元組的順序 。如果想要第乙個順序,第二個逆序,只需要在 x[1] 前面加上 -x[1]

lists = [(2, 5), (2, 3), (1, 2), (4, 2), (3, 4)]

lists.sort(key=lambda x: (x[0], x[1]))

print

(lists)

>>>[(1, 2), (2, 3), (2, 5), (3, 4), (4, 2)]

好,介紹完之後,下面進入正題,自定義順序 讀取檔案 多條件排序。

如圖,要讓下面這些檔案進行自己想要的順序排序,首先根據月份排,然後依據日期排;即先五月,從 5_1 到 5_15,然後再到 6_1 ,如果只是單純的採用 sort() 和sorted()肯定是不能實現的,需要自定義方式,進行排序。

那麼怎麼來排序呢?

思路就是: 先對檔案進行分割,得到 月份 和 天數,然後利用sort() 的key值,進行排序。

import

ospath = '

..\\url\\

'file_selected =os.listdir(path)

month = ['

jan', '

feb', '

mar', '

apr', '

may', '

jun', '

jul', '

aug', '

sep', '

oct', '

nov', '

dec'

]file_tem =

file_comp =

for file in

file_selected:

#[file]

value = file.split("

_")[1].split("

")[0]

ind = month.index(value) #

得到月份的下標

[file,ind]

num = int(file.split("

_")[1].split("

")[1]) #

得到天數

[file,ind,num]

得到[[file,ind,num],[file2,ind2,num2]]的形式

file_tem =

file_comp.sort(key=lambda x: (x[1], x[2])) #

根據ind排,再根據num2 排

sorted_file = [x[0] for x in

file_comp]

print(sorted_file)

最終得到結果:

['

comprehensive risk report_may 1_ 2019 9-00-36 am 076.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',

'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_jun 1_ 2019 9-00-27 am 541.html

']

python對目錄下的大量檔案處理

在用python對某一目錄下的多個檔案進行一一處理,會產生相應的多個結果。比如,在目錄 home jkx anaconda workspace task 2017 6 6 下有100個.txt 檔案,現在,用python對這100個檔案進行處理,會得到100個結果檔案,我們需要將得到的100個檔案自...

Python 遍歷目錄下的所有檔案

allfilenum 0 def printpath level,path global allfilenum 列印乙個目錄下的所有資料夾和檔案 所有資料夾,第乙個欄位是次目錄的級別 dirlist 所有檔案 filelist 返回乙個列表,其中包含在目錄條目的名稱 google翻譯 files o...

Python遞迴處理目錄下的檔案

使用os模組的os.walk 函式可以遞迴地遍歷目錄。os.walk top,topdown true,none,followlinks false top 要遍歷的目錄位址 topdown 遍歷優先順序。true為先遍歷top目錄,false為先遍歷top子目錄。目錄結構為 import os f...