First, you can use the string method startswith()
(docs here) to pick out the out the ones that have the right name. You do not need regex here since the names are at the beginning.
Then since the dates are structured nicely as YYYY-MM-DD you can sort the resulting list using sort()
or sorted()
(docs here) to get the most recent date.
Something like this:
def find_most_recent(file_list, prefix):
s_list = sorted([fname for fname in file_list if fname.startswith(prefix)])
return s_list[-1]
This uses list comprehension with an if
clause (docs here) to create a new list filtered to be just the file names starting with the passed in prefix. Then that list is sorted by passing it to sorted()
.
I did not bother with reversing the sort since it is just as easy to pick off the last entry in the list (using the -1 index on the s_list), but you could if you wanted to by using the option reverse=True
on sorted()
.
Note that startswith()
would have a problem here if the prefix/name could also be a substring of another valid name, but you indicated that this was not an issue and so it could be ignored for this use case.