================================================================================ PRACTICAL PYTHON SCRIPTING - CHALLENGE 1 SOLUTION Chapter 5: Building rebuild_typescript_course.py Challenge: Test File Discovery ================================================================================ PROBLEM: Create a script that: 1. Uses Path(__file__) to find its directory 2. Navigates to courses/Programming/TypeScript/html/ 3. Uses glob() to find all ts1-*.html files 4. Reports how many found and lists them SOLUTION: ================================================================================ from pathlib import Path def discover_chapters(): """Find all chapter HTML files.""" print("=" * 60) print("CHAPTER FILE DISCOVERY") print("=" * 60 + "\n") # Step 1: Find script's directory print("📍 Script location:") script_path = Path(__file__).resolve() script_dir = script_path.parent print(f" Script: {script_path}") print(f" Directory: {script_dir}\n") # Step 2: Navigate to chapters directory print("🗂️ Building path to chapters...") chapters_dir = script_dir / "courses" / "Programming" / "TypeScript" / "html" print(f" Expected path: {chapters_dir}\n") # Step 3: Check if directory exists print("🔍 Checking if directory exists...") if chapters_dir.exists(): print(f" ✅ Directory found!\n") else: print(f" ❌ Directory not found!") print(f" Please ensure chapters are at: {chapters_dir}\n") return # Step 4: Find all chapter files print("📚 Searching for chapter files (ts1-*.html)...\n") html_files = sorted(chapters_dir.glob("ts1-*.html")) if not html_files: print(" ⚠️ No chapter files found!\n") return # Step 5: Report results print(f" ✅ Found {len(html_files)} chapter file(s):\n") for i, file in enumerate(html_files, 1): file_size = file.stat().st_size print(f" {i:2d}. {file.name:30} ({file_size:,} bytes)") print() print("=" * 60) print(f"✅ DISCOVERY COMPLETE - Found {len(html_files)} chapters") print("=" * 60) if __name__ == "__main__": discover_chapters() ================================================================================ HOW IT WORKS: ================================================================================ 1. FIND SCRIPT DIRECTORY script_path = Path(__file__).resolve() script_dir = script_path.parent - __file__ = path to this script - .resolve() = convert to absolute path - .parent = directory containing the script 2. BUILD PATH TO CHAPTERS chapters_dir = script_dir / "courses" / "Programming" / "TypeScript" / "html" - Use / operator to build path step-by-step - Creates: /path/to/script/courses/Programming/TypeScript/html/ 3. CHECK IF EXISTS if chapters_dir.exists(): - .exists() returns True/False - Verifies directory before searching 4. FIND FILES WITH GLOB html_files = sorted(chapters_dir.glob("ts1-*.html")) - .glob("ts1-*.html") finds matching files - sorted() puts them in order (ts1-1, ts1-2, ts1-3, ...) 5. DISPLAY RESULTS for i, file in enumerate(html_files, 1): file_size = file.stat().st_size print(f"{i:2d}. {file.name} ({file_size:,} bytes)") - enumerate() gives number and file - .stat().st_size gives file size in bytes - Format nicely with aligned columns ================================================================================ TESTING: ================================================================================ python discover_chapters.py Output: ============================================================ CHAPTER FILE DISCOVERY ============================================================ 📍 Script location: Script: /var/www/myapp/discover_chapters.py Directory: /var/www/myapp 🗂️ Building path to chapters... Expected path: /var/www/myapp/courses/Programming/TypeScript/html 🔍 Checking if directory exists... ✅ Directory found! 📚 Searching for chapter files (ts1-*.html)... ✅ Found 12 chapter file(s): 1. ts1-1.html (45,234 bytes) 2. ts1-2.html (52,123 bytes) 3. ts1-3.html (48,456 bytes) ... 12. ts1-12.html (51,789 bytes) ============================================================ ✅ DISCOVERY COMPLETE - Found 12 chapters ============================================================ ================================================================================ KEY TAKEAWAYS: ================================================================================ ✅ Path(__file__).resolve().parent finds script directory ✅ Use / to build paths from base directory ✅ .exists() checks if directory exists ✅ .glob() finds files matching pattern ✅ sorted() orders results ✅ .stat().st_size gets file size ✅ enumerate() numbers items This is the foundation for all file discovery operations! ================================================================================