The Standard Library: Batteries Included
Python’s fame comes from its “Batteries Included” philosophy. When you install Python, you aren’t just getting a language; you’re getting a massive library of pre-written code that handles everything from cryptographic hashing to interacting with the operating system.
1. Files & Paths: pathlib (The Modern Standard)
Section titled “1. Files & Paths: pathlib (The Modern Standard)”In the old days, we used os.path for file manipulation. Modern Python uses pathlib, which treats files as objects rather than strings.
from pathlib import Path
# Create a path objectp = Path("docs") / "notes.txt" # Use '/' regardless of OS!
print(f"Filename: {p.name}")print(f"Extension: {p.suffix}")print(f"Exists? {p.exists()}")
# Read/Write without open/closeif p.exists(): content = p.read_text()2. Operating System & System: os and sys
Section titled “2. Operating System & System: os and sys”os: Low-level operating system tasks (environment variables, process IDs).sys: Interaction with the Python interpreter itself.
import osimport sys
# Get an environment variabledb_url = os.environ.get("DATABASE_URL")
# Get command line arguments (e.g., python script.py data.csv)filename = sys.argv[1] if len(sys.argv) > 1 else "default.csv"
# Check Python versionprint(f"Running on Python {sys.version}")3. Specialized Data: collections
Section titled “3. Specialized Data: collections”The collections module provides advanced alternatives to standard lists and dictionaries.
Counter: Automatically counts occurrences of items.defaultdict: A dictionary that creates missing keys automatically.deque: A list optimized for fast additions/removals from both ends.
from collections import Counter
inventory = ["apple", "banana", "apple", "cherry", "apple"]stats = Counter(inventory)print(stats["apple"]) # Output: 34. Dates & Times: datetime
Section titled “4. Dates & Times: datetime”Handling time is notoriously difficult (time zones, leap years). The datetime module makes it manageable.
from datetime import datetime, timedelta
now = datetime.now()one_week_later = now + timedelta(weeks=1)
# Format for displayprint(now.strftime("%B %d, %Y %H:%M")) # e.g., February 12, 2026 14:305. Other “Must-Know” Modules
Section titled “5. Other “Must-Know” Modules”| Module | Purpose |
|---|---|
json | Read and write JSON data for APIs. |
random | Generate random numbers and shuffle lists. |
math | Trigonometry, logarithms, and constants like pi and e. |
re | Regular Expressions for advanced text searching. |
hashlib | Secure hash algorithms (SHA-256) for passwords/data. |