Search for multiple files in folder with particular file name, and select the most recent file, or filename with the largest numeric value

Viewed 85

Total beginner here, I'm writing a program that searches for a particular string as file names in a folder, the folder has only PDFs.

For each file name I search for, typically it returns multiple files, like below:

200031-2018-252-20190828102708.pdf
200031-2018-252-20190828102735.pdf

but I'm only interested in opening the most recently created/modified file. In this care, it would be '200031-2018-252-20190828102735.pdf'

So two ways I can sort this:

1, either I select the most recent file, or 2, select the file with the largest numeric value.

Now I've written up until the code that can return the list of files with the same file name, but how do I select and open the most recent file?

Below is the code I've written so far:

import openpyxl
import pyperclip
import glob
import PyPDF2
import os
from pathlib import Path
import fitz

#define year
year='-2018'

#change directory of folder of where the documents are

os.chdir('G:\\Current Users\\Research analyst project management\\Tim\\PCC KPIs\\automate\\New folder')
#open excel file
wb=openpyxl.load_workbook('Grad_Rates_Audit_2017_New_vs_Old.xlsx')
#select sheet
sheet = wb["Campus"]


#assign variable to cell value
cell_value=str(sheet.cell(8,1).value)

#define search value
search_value=cell_value+year

#search for file name in folder
dir_path = Path('G:/Current Users/Research analyst project management/Tim/PCC KPIs/automate/New folder')
pdf_files = dir_path.glob('*.pdf')

for pdf_file in pdf_files:
        if search_value in pdf_file.name:
           print (pdf_file.name)

The 'print (pdf_file.name)' returns the following results:

200031-2018-252-20190828102708.pdf
200031-2018-252-20190828102735.pdf
    
1 Answers

You can use use the max function and pass to the key argument a slice of the filename containing only the timestamp. To achieve this you can use the .stem function, which uses the path returned from glob and returns the final path component without its suffix, after that slice the remaining string to get only the timestamp portion.

...
#search for file name in folder
dir_path = Path('G:/Current Users/Research analyst project management/Tim/PCC KPIs/automate/New folder')

list_of_files = dir_path.glob(f'*{search_value}*.pdf')
mostRecent = max(list_of_files, key=lambda fl: fl.stem[-13:])
Related