how do i extract the latest modified files?

What you have to do is:

  • first group the entries into different classes (by switch name)
  • then do the sorting for each class (converting the datetime properly)

See the example below:

import re
from datetime import datetime

content = [
    {'name': 'Switch-B3-110-Sep-12-07-36-36-29', 'date': '2020/09/22 07:36:42'},
    {'name': 'Switch-B3-110-Sep-12-07-36-36-29', 'date': '2020/09/12 07:36:42'},
    {'name': 'Switch-B3-110-Sep-12-07-36-36-29', 'date': '2020/09/15 07:36:42'},
    {'name': 'Switch-B3-110-Sep-12-07-36-36-29', 'date': '2020/09/1 07:36:42'},
    {'name': 'Switch-B1-110-Sep-12-07-36-36-29', 'date': '2020/09/22 07:36:42'},
    {'name': 'Switch-B1-110-Sep-12-07-36-36-29', 'date': '2020/09/12 07:36:42'},
    {'name': 'Switch-B2-110-Sep-12-07-36-36-29', 'date': '2020/09/15 07:36:42'},
    {'name': 'Switch-B2-110-Sep-12-07-36-36-29', 'date': '2020/09/1 07:36:42'}
]


# group by the switch name
data = {}
for f in content:
    # extract the switch name
    switch_type = re.match('^Switch-([A-Za-z0-9]+\-\d+).+$', f['name']).group(1)
    # initialize a new dictionary entry (if not exists)
    data[switch_type] = data.get(switch_type, [])
    data[switch_type].append(f) # append the item to it's group


# then do the sorting for each class
for switch, entries in data.items():
    sorted_entries = sorted(entries, key=lambda x: datetime.strptime(x['date'], "%Y/%m/%d %H:%M:%S"), reverse=True) # sorting by date in reverse
    print(switch, '-', sorted_entries[0]) # then 0 index becomes the latest entry for this switch type

output:

B3-110 - {'name': 'Switch-B3-110-Sep-12-07-36-36-29', 'date': '2020/09/22 07:36:42'}
B1-110 - {'name': 'Switch-B1-110-Sep-12-07-36-36-29', 'date': '2020/09/22 07:36:42'}
B2-110 - {'name': 'Switch-B2-110-Sep-12-07-36-36-29', 'date': '2020/09/15 07:36:42'}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top