How to Return the Most Recent Files from a Directory with Python

Using the glob library, we can quickly and dynamically pull a list of files from any directory and loop through them.

import glob

file_path = '/Downloads/*.xlsx'

files = sorted(glob.iglob(file_path), key=os.path.getctime, reverse=True)

This example pulls all the files in my downloads folder where the file type is .xlsx.

The files stored as a list in the files variable. You can pull any file by it’s index value, so files[0] will return the most recent file.

Iterate Through Excel Files

With the files in a list, we can iterate through them. In this example, I’ll loop through the files, grab the number of sheets in the file, then finally add them to my counter variable to get a sum of total tabs in my excel sheets.

import openpyxl

counter = 0

for i in files:
	counter += len(openpyxl.load_workbook(i).sheetnames)

print(counter)

Thanks for reading!


Posted

in

by

Tags: