Overview of Common Python Standard Library Modules
This article provides practical code examples for using key Python standard library modules—including os, sys, json, datetime, re, math, collections, urllib, random, and logging—to perform common tasks such as file operations, system info, data parsing, date handling, pattern matching, calculations, data structures, web requests, random generation, and logging.
os module : Provides methods for interacting with the operating system, including file and directory operations.
import os files = os.listdir('.') print(files)
sys module : Offers access to variables and functions used or maintained by the Python interpreter.
import sys print(sys.version)
json module : Enables encoding and decoding of JSON data.
import json data = '{"name": "John", "age": 30, "city": "New York"}' parsed_data = json.loads(data) print(parsed_data)
datetime module : Handles dates and times.
from datetime import datetime now = datetime.now() print(now.strftime("%Y-%m-%d %H:%M:%S"))
re module : Provides regular expression matching operations.
import re email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' text = "Contact me at [email protected]." matches = re.findall(email_pattern, text) print(matches)
math module : Contains mathematical functions.
import math print(math.pi)
collections module : Offers specialized container datatypes.
from collections import Counter words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] word_counts = Counter(words) print(word_counts)
urllib module : Supports fetching URLs (network data requests).
from urllib.request import urlopen url = 'http://www.example.com' response = urlopen(url) html = response.read().decode() print(html[:100])
random module : Used to generate random numbers.
import random random_float = random.random() print(random_float)
logging module : Provides a flexible logging system.
import logging logging.basicConfig(filename='app.log', level=logging.INFO) logging.info('This is an info message.')
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.