我需要第二个最新的文件。
在这个线程中找到了最新的:
Python get most recent file in a directory with certain extension
它使用了这个结构:
newest = min(glob.iglob('upload/*.log'), key=os.path.getctime)
但是,我怎样才能得到第二个元素而不是最小值或最大值呢?
请您参考如下方法:
我认为这是一个合适的解决方案:
# for the min + 1
sorted(glob.iglob('*.log'), key=os.path.getctime)[1]
# for the newest
sorted(glob.iglob('*.log'), key=os.path.getctime)[-1]
# for the second newest ( max - 1)
sorted(glob.iglob('*.log'), key=os.path.getctime)[-2]
所以基本上 glob.iglob('*.log') 只是一个数组(更准确地说,它的结果是一个生成器)——您可以按 ctime 对它进行排序并找到您想要的。
