Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Get the second latest file from a file pattern

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading