Explain Codes LogoExplain Codes Logo

How to get the latest file in a folder?

python
file-handling
pathlib
glob
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

Quickly find the newest file in a directory with this Python one-liner:

import os; latest_file = max((f for f in os.scandir('/your/directory')), key=lambda x: x.stat().st_mtime).name

The os.scandir() and lambda make a grand entrance, sorting by modification time (st_mtime) to directly give you the filename.

Picking the right attribute: getmtime vs getctime

When your goal is the latest file, the deciding attribute must be precise. Hint: Use os.path.getmtime rather than os.path.getctime. Why? getmtime returns the last modification time, which is more accurate than getctime, the file creation time.

Improving performance with glob

Handle multiple file formats while enhancing performance with glob.glob() or glob.iglob. You can specify file types like this: glob.glob('*.csv'), or use glob.iglob('*') to have a memory-efficient approach.

Embrace modernity with pathlib

Meet your friend pathlib, the modern approach for handling file paths! It not only makes your code more readable but also provides an object-oriented approach for pattern matching file names:

from pathlib import Path folder = Path('/your/directory') latest_file = max(folder.glob('*'), key=lambda x: x.stat().st_mtime).name # pathlib flexing on os.path!

Sometimes you may need to dive deeper and find the latest file across sub-directories or multiple directories. How? Simple. os.walk comes to your rescue. Combine it with the methods above and you'll be surfing through directories effortlessly.

Mind those error messages

Those pesky “FileNotFoundError” or “The system cannot find the file specified” errors often emerge from inaccurate file paths. Before blaming glob, double-check your file paths!

Get down with os and glob

Expand your toolkit with os.listdir() and os.path.join() to generate full file paths, or even os.path.abspath() to convert relative paths to absolute ones.

Be a responsible coder - test thoroughly

Before sending off your code into a production environment, remember to test it. In the wild, file systems can be unpredictable. Craft a test scenario with different file creation and modification times to verify your method works accurately.

Expect the unexpected

Embrace your role as a fortune teller. Incorporate exception handling to deal with unforeseen file access issues or permissions errors. A well-placed try-except block can make your code more robust and user-friendly.

Going beyond the latest file

Getting the latest file in a folder is just the beginning. With this knowledge, you can organize, archive, or process files based on creation or modification times. The possibilities are endless!