I have a list of files that match a particular pattern from which I need to get the latest and the second latest file paths.
I am able to get the latest file using the code below
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)
Is there a way to get the second latest file from the above file pattern?
>Solution :
You could sort list_of_files, then use index [-2], to get the second last item:
list_of_files = glob.glob('/tmp/*.json')
latest_file = sorted(list_of_files, key=os.path.getctime)
print(latest_file[-2])