Skip to main content Brad's PyNotes

Stdlib Tour Tutorial

TL;DR

Python’s standard library provides essential modules for OS operations, file handling, math, networking, dates, and performance measurement - “batteries included”!

Interesting!

Python’s standard library is so comprehensive that many tasks don’t require external dependencies - from web requests to compression, it’s all built-in!

Operating System Interface

python code snippet start

import os
import glob

# File system operations
os.getcwd()                    # Current directory
os.chdir('/path/to/directory') # Change directory
os.system('ls -la')           # Run shell command

# Find files with patterns
glob.glob('*.py')             # All Python files
glob.glob('**/test_*.py', recursive=True)  # Recursive search

python code snippet end

System Tools

python code snippet start

import sys

# Command line arguments
print(sys.argv)  # ['script.py', 'arg1', 'arg2']

# Exit program
sys.exit('Error: something went wrong')

# Input/output redirection
sys.stderr.write('Error message\n')

python code snippet end

Text Processing

python code snippet start

import re

# Regular expressions
text = "The rain in Spain falls mainly in the plain"
re.findall(r'\b\w*ain\w*\b', text)  # ['rain', 'Spain', 'mainly', 'plain']

# Pattern matching
if re.match(r'\d{3}-\d{2}-\d{4}', '123-45-6789'):
    print("Valid SSN format")

python code snippet end

Mathematics

python code snippet start

import math
import random

# Math operations
math.cos(math.pi / 4)  # 0.7071067811865476
math.log(1024, 2)      # 10.0 (log base 2)

# Random operations
random.choice(['apple', 'pear', 'banana'])  # Random selection
random.sample(range(100), 10)               # 10 random numbers
random.random()                             # Random float [0.0, 1.0)

python code snippet end

Internet Access

python code snippet start

from urllib.request import urlopen

# Fetch web data
with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
    for line in response:
        line = line.decode('utf-8')
        if line.startswith('datetime'):
            print(line.rstrip())

python code snippet end

Dates and Times

python code snippet start

from datetime import date

# Date operations
now = date.today()
birthday = date(1964, 7, 31)
age = now - birthday
print(f"Age: {age.days} days")

# Date formatting
now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

python code snippet end

Data Compression

python code snippet start

import zlib

# Compress text
s = b'witch which has which witches wrist watch'
compressed = zlib.compress(s)
print(f"Original: {len(s)}, Compressed: {len(compressed)}")

# Decompress
original = zlib.decompress(compressed)

python code snippet end

Performance Measurement

python code snippet start

from timeit import Timer

# Compare performance
Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
Timer('a,b = b,a', 'a=1; b=2').timeit()

# Quick timing
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

python code snippet end

Python’s standard library truly embodies “batteries included” - providing powerful, production-ready tools without external dependencies! Continue exploring with part 2 of the standard library tour for more advanced modules and features.

Reference: Brief Tour of the Standard Library