【问题标题】:Python - Get the second latest file from a file patternPython - 从文件模式中获取第二个最新文件
【发布时间】:2022-01-11 16:07:39
【问题描述】:

我有一个与特定模式匹配的文件列表,我需要从中获取最新的和第二个最新的文件路径。

我可以使用以下代码获取最新文件

import glob
import os

list_of_files = glob.glob('/home/yash/proj_dir/reference_data/*/FeaturesV3.txt')
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

有没有办法从上述文件模式中获取第二个最新的文件?

【问题讨论】:

标签: python python-3.x list file


【解决方案1】:

您可以排序list_of_files,然后使用索引[-2],得到倒数第二项:

list_of_files = glob.glob('/tmp/*.json')
latest_file = sorted(list_of_files, key=os.path.getctime)
print(latest_file[-2])

【讨论】:

  • 是的,这就是工作。
猜你喜欢
  • 2023-04-09
  • 2013-05-13
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多