Find the oldest modified file in a directory and its sub-directories with Python 3.8

Question:

I am working on a small file sorting program, I’ve come across a problem where I can’t figure out how to find the oldest modified file in a file directory that also has many subfolders. I’ve tried os.walk but I wasn’t successful with it. Any help is appreciated!

Asked By: chsoreal

||

Answers:

Welcome to SO! Please provide a minimal, reproducible example so that we can know what you’ve tried so far and help you.

You could use os.scandir() to recursively traverse the directory tree and get a list of files, sort them by st_mtime, and return the earliest modified one.

import os

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in os.scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)
        else:
            yield entry


def get_oldest_file(directory_name):
    files = []

    for file in scantree(directory_name):
        files.append((file.stat().st_mtime, file.path))

    files.sort(key=lambda x:x[0])
    return files[0][1]
Answered By: thariqfahry
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.