[英]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. 嗯,这里有几种可能的解决方法。
sorted_list[0]
and sorted_list[1]
. sorted_list[0]
和sorted_list[1]
。 Maybe that will give you a more promising result 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
第二的项目。 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.