Skip to content

Chapter 10: Common Standard Libraries

os — Operating System Interaction

bash
import os

# Current working directory
print(f"Current directory: {os.getcwd()}")

# List directory contents
files = os.listdir(".")
print(f"Current directory contains {len(files)} file(s)/folder(s)")

# Create directories
os.makedirs("test_dir/sub_dir", exist_ok=True)
print("Directory created")

# Path operations (recommend using os.path or pathlib)
file_path = os.path.join("test_dir", "sub_dir", "data.txt")
print(f"Joined path: {file_path}")
print(f"File name: {os.path.basename(file_path)}")
print(f"Directory name: {os.path.dirname(file_path)}")
print(f"File exists? {os.path.exists(file_path)}")
bash
Current directory: /home/user/project
Current directory contains 5 file(s)/folder(s)
Directory created
Joined path: test_dir/sub_dir/data.txt
File name: data.txt
Directory name: test_dir/sub_dir
File exists? False

datetime — Date and Time

bash
from datetime import datetime, timedelta

now = datetime.now()
print(f"Current time: {now}")
print(f"Formatted: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Weekday {now.isoweekday()}")

# Time arithmetic
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")
print(f"Last week: {last_week.strftime('%Y-%m-%d')}")

# String → Date
birthday = datetime.strptime("1999-06-15", "%Y-%m-%d")
age_days = (now - birthday).days
print(f"You have lived {age_days} days (about {age_days // 365} years)")
bash
Current time: 2025-06-20 14:30:25.123456
Formatted: 2025-06-20 14:30:25
Weekday 5
Tomorrow: 2025-06-21
Last week: 2025-06-13
You have lived 9496 days (about 25 years)

re — Regular Expressions

bash
import re

text = "My phone number is 13812345678, email is test@example.com, backup: hello_world@gmail.com"

# Extract phone numbers
phone = re.search(r'1[3-9]\d{9}', text)
print(f"Phone number: {phone.group()}")

# Extract all emails
emails = re.findall(r'[\w.-]+@[\w.-]+\.\w+', text)
print(f"Emails: {emails}")

# Replace sensitive information
masked = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1\2', text)
print(f"Masked: {masked}")

# Validate format
is_valid = bool(re.match(r'^\d{6}$', "100086"))
print(f"Postal code valid: {is_valid}")
bash
Phone number: 13812345678
Emails: ['test@example.com', 'hello_world@gmail.com']
Masked: My phone number is 1385678, email is test@example.com, backup: hello_world@gmail.com
Postal code valid: True

collections — Enhanced Collections

bash
from collections import Counter, defaultdict, namedtuple

# Counter: frequency counter
words = "the quick brown fox jumps over the lazy dog the fox".split()
count = Counter(words)
print("Word frequency:")
for word, freq in count.most_common(3):
    print(f"  '{word}' appears {freq} time(s)")

# defaultdict: dictionary with default values
grades = defaultdict(list)
scores = [("Math", 85), ("Language", 92), ("Math", 78), ("English", 90), ("Language", 88)]
for subject, score in scores:
    grades[subject].append(score)
print(f"\nGrades by subject: {dict(grades)}")

# namedtuple: named tuples
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(f"\nPoint: ({p.x}, {p.y})")
bash
Word frequency:
  'the' appears 3 time(s)
  'fox' appears 2 time(s)
  'quick' appears 1 time(s)

Grades by subject: {'Math': [85, 78], 'Language': [92, 88], 'English': [90]}

Point: (3, 4)

itertools — Iteration Tools

bash
import itertools

# Infinite counter
counter = itertools.count(start=1, step=2)
first_five = [next(counter) for _ in range(5)]
print(f"Odd sequence: {first_five}")

# Permutations and combinations
items = ["A", "B", "C"]
perms = list(itertools.permutations(items, 2))
print(f"Permutations P(3,2): {perms}")

combos = list(itertools.combinations(items, 2))
print(f"Combinations C(3,2): {combos}")

# Grouping
data = sorted([("animal", "cat"), ("fruit", "apple"), ("animal", "dog"), ("fruit", "banana")],
              key=lambda x: x[0])
for key, group in itertools.groupby(data, key=lambda x: x[0]):
    items_in_group = [item[1] for item in group]
    print(f"  {key}: {items_in_group}")
bash
Odd sequence: [1, 3, 5, 7, 9]
Permutations P(3,2): [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
Combinations C(3,2): [('A', 'B'), ('A', 'C'), ('B', 'C')]
  animal: ['cat', 'dog']
  fruit: ['apple', 'banana']
bash
import sys

print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
print(f"Default encoding: {sys.getdefaultencoding()}")
print(f"Recursion depth limit: {sys.getrecursionlimit()}")
print(f"Command-line arguments: {sys.argv}")

# View number of installed modules
print(f"Loaded module count: {len(sys.modules)}")
bash
Python version: 3.12.4 (main, Jun  8 2025, 11:20:00) [GCC 11.4.0]
Platform: linux
Default encoding: utf-8
Recursion depth limit: 1000
Command-line arguments: ['script.py']
Loaded module count: 67