Python实现查询某个目录下修改时间最新的文件示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现查询某个目录下修改时间最新的文件。分享给大家供大家参考,具体如下:

通过Python脚本,查询出某个目录下修改时间最新的文件。

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

直接撸代码:

# -*- coding: utf-8 -*-
import os
import shutil
def listdir(path, list_name): #传入存储的list
 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.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'C:\Users\Administrator\Desktop\img'
list = []
listdir(p, list)
new_file = newestfile(list)
print('from:',new_file[0])
print('to:',shutil.copy(new_file[0], 'C:\\Users\\Administrator\\Desktop\\img\\a.xml'))

运行结果:

('newest file is', ('C:\\Users\\Administrator\\Desktop\\img\\logo.gif', 1535508866.833419))
('from:', 'C:\\Users\\Administrator\\Desktop\\img\\logo.gif')
('to:', None)

方法说明:

def listdir(path, list_name): #传入存储的list
 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.getctime(file_path))) #把文件路径,文件创建时间加入list中

def newestfile(target_list): #传入包含文件路径,文件创建时间的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

shutil.copy(new_file[0], 'C:\\Users\\Administrator\\Desktop\\img\\a.xml') #文件拷贝

补充:shutil.copy(source, destination)的使用说明

shutil.copy(source, destination)(这种复制形式使用的前提是必须要有 os.chdir(你要处理的路径)

source/destination 都是字符串形式的路劲,其中destination是:

  • 1、可以是一个文件的名称,则将source文件复制为新名称的destination
  • 2、可以是一个文件夹,则将source文件复制到destination中
  • 3、若这个文件夹不存在,则将source目标文件内的内容复制到destination中

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 反编译exe文件为py文件的实例代码

我们用pyinstaller把朋友文件打包成exe文件,但有时候我们需要还原,我们可以用pyinstxtractor.py 用法: python pyinstxtractor.py xx...

python调用opencv实现猫脸检测功能

python调用opencv实现猫脸检测功能

Python 小猫检测,通过调用opencv自带的猫脸检测的分类器进行检测。 分类器有两个:haarcascade_frontalcatface.xml和 haarcascade_fr...

使用OpenCV实现仿射变换—缩放功能

使用OpenCV实现仿射变换—缩放功能

前面介绍怎么样实现平移的功能,接着下来演示缩放功能。比如在一个文档里插入一个图片,发现这个图片占用太大的面积了,要把它缩小,才放得下,与文字的比例才合适。这样的需求,就需要使用仿射变换的...

Python numpy实现数组合并实例(vstack,hstack)

若干个数组可以沿不同的轴合合并到一起,vstack,hstack的简单用法, >>> a = np.floor(10*np.random.random((2,2))...

详解python执行shell脚本创建用户及相关操作

用户发送请求,返回帐号和密码 ###利用框架flask 整体思路: # 目的:实现简单的登录的逻辑 # 1需要get和post请求方式 需要判断请求方式 # 2获取参数...