I have the following directory format:
logs
---- abc_090000_20210124
---- abc_091500_20210124
etc...
The format is abc_(HHMMSS)_(YYYYMMDD)
I want to get the two most recent files by date and time.
If they are all on the same day I use this code:
directory = os.listdir("logs")
base = "abc"
date = sorted([x.split("_")[2] for x in directory])[-1]
t_of_day = sorted([x.split("_")[1] for x in directory if x.split("_")[2] == date])
a = f"logs/{base}_{t_of_day[-1]}_{date}"
b = f"logs/{base}_{t_of_day[-2]}_{date}"
print(a,b)
and it works properly, however, at the change of day the files will change like so:
...
---- abc_234506_20210124
---- abc_000007_20210125
...
and my code will give an error as there will not be two values in the list t_of_day.
I am unsure of how I could change this to suit my situation.
I have tried to use a condition where if date[-1] == date[-2] to use a different value, but as the dataset builds up this may become unreliable.
Is there perhaps an alternative way to sort the files? I must state that changing the file names is not an option.