Dosyaları ve tarihleri bir liste halinde toplayın ve bu listeyi tarih öğesine göre sıralayın. İşte örnek kodu içinde comments bunu anlamak yeterli olmalıdır: ... kod daha kompakt ve temiz hale getirmek için bir liste anlama kullanabilirsiniz
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
file_date_tuple_list = []
for x in files:
d = os.path.getmtime(x)
#tuple with file and date, add it in a list
file_date_tuple = (x,d)
file_date_tuple_list.append(file_date_tuple)
#sort the tuple list by the second element which is the date
file_date_tuple_list.sort(key=lambda x: x[1])
İsteğe
file_date_tuple_list = [(x,os.path.getmtime(x)) for x in files]
file_date_tuple_list.sort(key=lambda x: x[1])
Bu iki satır, ilk örnekte tüm for
döngüsünü değiştirir.
Şimdi ne listede istediğiniz modifikasyon zaman damgasını alan bir dosya adı ve ardından biçimlendirilmiş tarih ... eklemek Bu ithalat ile dize ...
from datetime import date
ve bu liste anlayışı ile başka bir satır ise ve bir dizeye biçimlendirir. Gördüğünüz gibi belirli datetime
from datetime import datetime
limit = datetime(2011,01,05,17,0,0) #5pm , Jun 5 2011
file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \
for x in file_date_tuple_list \
if datetime.fromtimestamp(x[1]) > limit ]
tarih sınırlandırılması için
file_date_tuple_list.sort(key=lambda x: x[1],reverse=True)
: türden sırasını sort
yürütülmesinde opsiyonel parametre reverse
kullanmak tersine için
file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \
for x in file_date_tuple_list]
liste anlamında bir if
koşulu ekleyebilirsiniz, bu gerçekten harika.
'key = lambda x: os.path.getmtime (x)' -> 'anahtar = os.path.getmtime' –