Skip to content

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.

path_logic.py
from pathlib import Path
# Create a path object
p = 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/close
if p.exists():
content = p.read_text()

  • os: Low-level operating system tasks (environment variables, process IDs).
  • sys: Interaction with the Python interpreter itself.
system.py
import os
import sys
# Get an environment variable
db_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 version
print(f"Running on Python {sys.version}")

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.
collections_demo.py
from collections import Counter
inventory = ["apple", "banana", "apple", "cherry", "apple"]
stats = Counter(inventory)
print(stats["apple"]) # Output: 3

Handling time is notoriously difficult (time zones, leap years). The datetime module makes it manageable.

time_handling.py
from datetime import datetime, timedelta
now = datetime.now()
one_week_later = now + timedelta(weeks=1)
# Format for display
print(now.strftime("%B %d, %Y %H:%M")) # e.g., February 12, 2026 14:30

ModulePurpose
jsonRead and write JSON data for APIs.
randomGenerate random numbers and shuffle lists.
mathTrigonometry, logarithms, and constants like pi and e.
reRegular Expressions for advanced text searching.
hashlibSecure hash algorithms (SHA-256) for passwords/data.