gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Write Python program that accept path to dir via command line and prints last 5 files in…
- User
Write Python program that accept path to dir via command line and prints last 5 files in it and its subdirs.
- Assistant
Sure! Below is a Python program that accepts a directory path via the command line and prints the last 5 modified files in that directory and its subdirectories:
import os import sys from pathlib import Path def get_last_5_files(directory): files = [] # Traverse directory and subdirectories for root, dirs, filenames in os.walk(directory): for filename in filenames: filepath = Path(root) / filename try: mtime = filepath.stat().st_mtime files.append((filepath, mtime)) except FileNotFoundError: # File might have been deleted between os.walk and stat pass # Sort files by modification time in descending order (newest first) files.sort(key=lambda x: x[1], reverse=True) # Get last 5 files (most recently modified files) last_5_files = files[:5] return last_5_files def main(): if len(sys.argv) != 2: print("Usage: python script.py <directory_path>") sys.exit(1) directory = sys.argv[1] if not os.path.isdir(directory): print(f"Error: {directory} is not a valid directory.") sys.exit(1) last_files = get_last_5_files(directory) if not last_files: print("No files found in the directory.") else: print("Last 5 modified files (newest first):") for filepath, mtime in last_files: print(f"{filepath} - Last Modified Time: {mtime}") if __name__ == "__main__": main()