简体   繁体   English

获取文件夹中的第二个最新文件

[英]Get second newest file in a folder

I am trying to get most recent and second most recent file in a directory. 我正在尝试获取目录中的最新文件和第二最新文件。 here is my code 这是我的代码

import glob
import os

path = r'C:\temp\Processed\*'
list_of_files = glob.glob(path) # * means all if need specific format then *.csv
sorted_files = sorted(list_of_files, key=os.path.getctime)
print sorted_files[-1]
print sorted_files[-2]

Reference: Second newest file 参考: 最新文件

latest_file[-1] returns the newest file ( 170608_191655__Equity_Watched.csv ), but latest_file[-2] gives me a 170607_082445__Equity_Watched.csv which is not the second most recent. latest_file[-1]返回最新的文件( 170608_191655__Equity_Watched.csv ),但是latest_file[-2]给我的是170607_082445__Equity_Watched.csv ,它不是第二最新的文件。 I was expecting to get 170607_231353__Equity_Watched.csv . 我期望得到170607_231353__Equity_Watched.csv

在此处输入图片说明

Any idea what am I doing wrong? 知道我在做什么错吗?

看起来您实际上想要的是getmtime ,而不是getctime (因为您正在向我们展示一个显示修改时间的屏幕截图)。

Hmm, here are a couple ways to possible go about it. 嗯,这里有几种可能的解决方法。

  1. Reverse the sort. 反转排序。 Sort it in the other direction and try accessing sorted_list[0] and sorted_list[1] . 从另一个方向对其进行排序,然后尝试访问sorted_list[0]sorted_list[1] Maybe that will give you a more promising result 也许那会给你带来更美好的结果
  2. Access file in the list and sort yourself. 访问列表中的文件并对自己进行排序。 You could loop through the list, run os.path.getctime on them, and use that data to find the recent and second most recent items yourself. 您可以遍历该列表,对它们运行os.path.getctime ,然后使用该数据自己查找最新的和os.path.getctime第二的项目。
  3. Continue to google or wait on another answer. 继续使用Google或等待其他答案。 Or use getmtime as Stefan mentioned... 或使用Stefan提到的getmtime ...

Best of luck! 祝你好运!

sorted_files = sorted(list_of_files, key=os.path.getmtime)
print sorted_files[-2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM