Python Basics — Standard Library Tour

3 minute read

Standard Library Tour

Python’s standard library is one of its biggest strengths — “batteries included.” Here’s a guided tour of the modules you’ll use most often.

os — File System Operations

import os

# Current working directory
print(os.getcwd())  # /Users/you/project

# List files in a directory
print(os.listdir("."))  # ['main.py', 'data/', 'README.md']

# Check if a file/directory exists
print(os.path.exists("main.py"))     # True
print(os.path.isfile("main.py"))     # True
print(os.path.isdir("data"))         # True

# Join paths (cross-platform)
path = os.path.join("data", "users", "alice.json")
print(path)  # data/users/alice.json (or data\users\alice.json on Windows)

# Get file info
print(os.path.getsize("main.py"))    # file size in bytes
print(os.path.basename("/a/b/c.py")) # c.py
print(os.path.dirname("/a/b/c.py"))  # /a/b

# Environment variables
print(os.environ.get("HOME", "not set"))

sys — System Parameters

import sys

print(sys.version)          # 3.12.0 (main, Oct  2 2023, ...)
print(sys.platform)         # darwin (macOS), linux, win32
print(sys.path[:3])         # Module search paths
print(sys.argv)             # Command-line arguments

# Exit a program
# sys.exit(0)   # 0 = success, 1 = error

datetime — Dates and Times

from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
print(now)                    # 2025-03-03 14:30:00.123456
print(now.strftime("%Y-%m-%d %H:%M"))  # 2025-03-03 14:30

# Today's date
today = date.today()
print(today)                  # 2025-03-03
print(today.year, today.month, today.day)  # 2025 3 3

# Create a specific date
birthday = date(1995, 8, 15)
print(birthday)               # 1995-08-15

# Date arithmetic
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
print(f"Tomorrow: {tomorrow}")     # 2025-03-04
print(f"Last week: {last_week}")   # 2025-02-24

# Difference between dates
age_days = (today - birthday).days
print(f"Age in days: {age_days}")  # ~10792

# Parse a date string
parsed = datetime.strptime("2025-03-03", "%Y-%m-%d")
print(parsed)  # 2025-03-03 00:00:00

math — Mathematical Functions

import math

print(math.pi)         # 3.141592653589793
print(math.e)          # 2.718281828459045
print(math.sqrt(144))  # 12.0
print(math.pow(2, 10)) # 1024.0
print(math.log(100))   # 4.605... (natural log)
print(math.log10(100)) # 2.0
print(math.ceil(4.1))  # 5
print(math.floor(4.9)) # 4
print(math.factorial(5))  # 120
print(math.gcd(12, 8))   # 4

collections — Specialized Containers

from collections import Counter, defaultdict, namedtuple, deque

# Counter — count occurrences
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count)                 # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(count.most_common(2))  # [('apple', 3), ('banana', 2)]

# defaultdict — dict with default values
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
dd["veggies"].append("carrot")
print(dict(dd))  # {'fruits': ['apple', 'banana'], 'veggies': ['carrot']}

# namedtuple — lightweight class
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)   # 3 4
print(p)           # Point(x=3, y=4)

# deque — fast append/pop from both ends
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)  # deque([0, 1, 2, 3, 4])

json — JSON Encoding/Decoding

import json

# Python dict → JSON string
data = {"name": "Alice", "age": 30, "scores": [85, 92, 78]}
json_string = json.dumps(data, indent=2)
print(json_string)
# {
#   "name": "Alice",
#   "age": 30,
#   "scores": [85, 92, 78]
# }

# JSON string → Python dict
parsed = json.loads(json_string)
print(parsed["name"])  # Alice

Top 20 Standard Library Modules

Module Purpose Common Use
os Operating system interface File paths, directories
sys System parameters Command-line arguments, exit
datetime Date and time Timestamps, date math
math Math functions sqrt, pi, ceil, floor
json JSON encoding/decoding API data, config files
csv CSV file handling Reading/writing spreadsheets
collections Special containers Counter, defaultdict, deque
pathlib Modern file paths Path manipulation
re Regular expressions Pattern matching
random Random numbers Shuffling, sampling
itertools Iterator tools Combinations, permutations
functools Functional tools reduce, lru_cache, partial
string String constants ascii_letters, digits
typing Type hints Type annotations
logging Logging Debug, info, warning, error
unittest Testing framework Unit tests
argparse CLI argument parsing Command-line tools
sqlite3 SQLite database Lightweight DB
hashlib Hashing SHA256, MD5
http.server Simple HTTP server Quick file serving

Quick Examples

# random
import random
print(random.randint(1, 100))         # random int between 1-100
print(random.choice(["a", "b", "c"])) # random pick
print(random.shuffle([1, 2, 3, 4]))   # shuffle in-place

# pathlib — modern file paths
from pathlib import Path
p = Path("data") / "users" / "alice.json"
print(p)            # data/users/alice.json
print(p.suffix)     # .json
print(p.stem)       # alice
print(p.exists())   # False (unless the file exists)

# re — regular expressions
import re
matches = re.findall(r"\d+", "Order 123 has 5 items worth $250")
print(matches)  # ['123', '5', '250']

Summary

  • Python’s standard library has over 200 modules — no installation needed
  • os, sys, datetime, math, json, collections are the most commonly used
  • pathlib is the modern replacement for os.path
  • Use dir(module) and help(module.function) to explore any module
  • Check the official docs for the full reference

Next up: Creating Modules →

Updated: