1. 程式人生 > 實用技巧 >檔案列表,根據修改時間排序

檔案列表,根據修改時間排序

code res.sort(key=lambda fn: os.path.getmtime(os.path.join(folder_storage,fn["name"])),reverse = True)
# 方法一
import os
def listdir(path, list_name):
    """
    將檔案路徑和修改時間存入列表中
    :param path: 資料夾的絕對路徑
    :param list_name: 空列表
    :return:
    """
    for file in os.listdir(path):  # 對目錄中的所有檔案進行遍歷
        file_path 
= os.path.join(path, file) # 檔案的路徑 if os.path.isdir(file_path): # 如果拼接後的還是目錄,進行遞迴 listdir(file_path, list_name) else: # 如果拼接之後,還是檔案,就將元組形式存到列表 list_name.append((file_path, os.path.getmtime(file_path))) def newestfile(target_list): """ 找出最新修改的檔案 :param target_list: 存有檔案路徑和修改時間的列表 :
return: 最新的檔案 """ newest_file = target_list[0] # 預設第一個元組中的檔案是最新的 for i in range(len(target_list)): # 對列表進行遍歷 if i < (len(target_list) - 1) and newest_file[1] < target_list[i + 1][1]: newest_file = target_list[i + 1] else: continue print(
'newest file is', newest_file) return newest_file p = r'G:\test_demo' list = [] listdir(p, list) new_file = newestfile(list) # 方法二 def new_report(test_report): lists = os.listdir(test_report) # 列出目錄的下所有檔案和資料夾儲存到lists lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn)) # 按時間排序 file_new = os.path.join(test_report, lists[-1]) # 獲取最新的檔案儲存到file_new return file_new file_new = new_report("G:\\test_demo") print(file_new)