Skip to content

Instantly share code, notes, and snippets.

@horvatha
Last active April 14, 2024 14:23
Show Gist options
  • Save horvatha/74cef12dacc97a1509b981e514be4320 to your computer and use it in GitHub Desktop.
Save horvatha/74cef12dacc97a1509b981e514be4320 to your computer and use it in GitHub Desktop.
import argparse
from pathlib import Path
import os
def get_latest_file(directory: Path) -> Path:
"""
Finds the most recently modified file in a directory and its subdirectories.
Args:
directory: A pathlib.Path object representing the directory to search.
Returns:
The pathlib.Path object of the most recently modified file, or None if no files are found.
"""
latest_file = None
latest_mtime = None
for item in directory.rglob("*"):
if item.is_file():
try:
mtime = item.stat().st_mtime
except OSError:
... # Ignore errors caused by broken symlinks
if latest_file is None or mtime > latest_mtime:
latest_file = item
latest_mtime = mtime
return latest_file
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Find the latest modified file.")
parser.add_argument("directory", type=Path, help="Path to the directory to search.")
args = parser.parse_args()
latest_file = get_latest_file(args.directory)
if latest_file:
print(f"The most recently modified file is: {latest_file}")
else:
print("No files found in the directory or its subdirectories.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment