美文网首页
查询出某个目录下最新修改时间的文件

查询出某个目录下最新修改时间的文件

作者: 一片冰心一生平安 | 来源:发表于2018-06-14 18:30 被阅读0次

应用场景举例:
       比如有时候需要从ftp上拷贝自己刚刚上传的文件,那么这时就需要判断哪个文件的修改时间是最新的,即最后修改的文件是我们的目标文件。



# -*- coding: UTF-8 -*-


import os
import shutil


def listdir(path, list_name):
    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中
            list_name.append((file_path,os.path.getctime(file_path)))


def newestfile(target_list):
    # 冒泡算法找出时间最大的
    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'C:\Users\WMB\700c-4'
p = r'E:\python_code\filetest'
listname = []
listdir(p, listname)
new_file = newestfile(listname)
print('from:', new_file[0])
# 文件拷贝
print('to:', shutil.copy(new_file[0], 'E:\\python_code\\filetest\\a.txt'))

相关文章

网友评论

      本文标题:查询出某个目录下最新修改时间的文件

      本文链接:https://www.haomeiwen.com/subject/xkxueftx.html