zoukankan      html  css  js  c++  java
  • 文件列表,根据修改时间排序

    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:	est_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) 
     
     
     
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    数据模型Model(I)
    泛型
    iOS开发之widget实现
    ios断点续传:NSURLSession和NSURLSessionDataTask实现
    iOS 直播类APP开发流程解析
    iOS实现电话状态监听 CoreTelephony
    iOS9全新的联系人相关框架——Contacts Framework
    iOS开发集成微信支付
    如何在 Git 里撤销(几乎)任何操作
    iOS开发网络缓存原理
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14192631.html
Copyright © 2011-2022 走看看