Reputation: 29
I want to grab latest file from the list of files which comes with timestamp.
For example:
today_file = 02022022
list_file = ['f_mortgage_portfolio_29012022','f_mortgage_portfolio_30012022','f_mortgage_portfolio_31012022','f_mortgage_portfolio_01022022']
If my today_file
date found in the list_file
, then return
the file name; Else it should return
last latest file from the list which is f_mortgage_portfolio_01022022
based on the date value
Upvotes: 0
Views: 42
Reputation: 521073
We can sort the list using a lambda function, descending by date, and then take the first entry:
list_file = ['f_mortgage_portfolio_29012022', 'f_mortgage_portfolio_30012022', 'f_mortgage_portfolio_31012022', 'f_mortgage_portfolio_01022022']
latest_file = sorted(list_file, key=lambda x: x.rsplit('_', 1)[1][4:8] + x.rsplit('_', 1)[1][2:4] + x.rsplit('_', 1)[1][0:2], reverse=True)[0]
print(latest_file) # f_mortgage_portfolio_01022022
For an explanation of the lambda function used above, starting with an input of f_mortgage_portfolio_01022022
, we split on the last underscore to first obtain 01022022
. Then we build a date string 20220201
, which is in a sortable ISO format. This allows the lambda function to sort the file names descending by date.
Upvotes: 1