Reputation: 3
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!
Upvotes: 0
Views: 286
Reputation: 439
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]
Upvotes: 1