Python获取文件最新的修改时间

# 方法一
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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值