Python - 从文件模式中获取第二个最新文件
Python - Get the second latest file from a file pattern
我有一个匹配特定模式的文件列表,我需要从中获取最新和第二个最新的文件路径。
我可以使用下面的代码获取最新文件
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)
有没有办法从上述文件模式中获取第二个最新文件?
您可以排序 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])
我有一个匹配特定模式的文件列表,我需要从中获取最新和第二个最新的文件路径。
我可以使用下面的代码获取最新文件
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)
有没有办法从上述文件模式中获取第二个最新文件?
您可以排序 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])