The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a _recent documents_ search CLI

Here’s a simple command-line interface (CLI) in Python to search for recent documents in a given directory, sorted by modification time, and filtered optionally by keyword and file type:

python
import os import argparse from datetime import datetime, timedelta def find_recent_files(directory, days, keyword=None, filetypes=None, limit=10): current_time = datetime.now() recent_files = [] for root, dirs, files in os.walk(directory): for file in files: if filetypes and not any(file.endswith(ext) for ext in filetypes): continue if keyword and keyword.lower() not in file.lower(): continue file_path = os.path.join(root, file) try: mod_time = datetime.fromtimestamp(os.path.getmtime(file_path)) if mod_time >= current_time - timedelta(days=days): recent_files.append((file_path, mod_time)) except Exception as e: print(f"Error accessing {file_path}: {e}") # Sort by most recent modification time recent_files.sort(key=lambda x: x[1], reverse=True) return recent_files[:limit] def main(): parser = argparse.ArgumentParser(description='Search for recent documents in a directory.') parser.add_argument('directory', help='Directory to search in') parser.add_argument('--days', type=int, default=7, help='Number of days to look back') parser.add_argument('--keyword', help='Keyword to search in file names') parser.add_argument('--filetypes', nargs='+', help='List of file extensions to include (e.g. .txt .docx .pdf)') parser.add_argument('--limit', type=int, default=10, help='Max number of results to show') args = parser.parse_args() results = find_recent_files(args.directory, args.days, args.keyword, args.filetypes, args.limit) if results: print(f"nRecent files in the last {args.days} days:n") for path, mod_time in results: print(f"{mod_time.strftime('%Y-%m-%d %H:%M:%S')} - {path}") else: print("No recent files found.") if __name__ == '__main__': main()

Example Usage

bash
python recent_docs_cli.py /home/user/Documents --days 5 --keyword report --filetypes .txt .pdf --limit 20

This will search for recent .txt and .pdf files with “report” in the name, modified within the last 5 days, limited to 20 results.

Let me know if you’d like it packaged as an installable CLI tool (e.g., using setuptools or Typer).

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About