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<br>files = os.listdir('.')<br>print(files) sys module : Offers access to variables and functions used or maintained by the Python interpreter. import sys<br>print(sys.version) json module : Enables encoding and decoding of JSON data.
import json<br>data = '{"name": "John", "age": 30, "city": "New York"}'<br>parsed_data = json.loads(data)<br>print(parsed_data)datetime module : Handles dates and times.
from datetime import datetime<br>now = datetime.now()<br>print(now.strftime("%Y-%m-%d %H:%M:%S"))re module : Provides regular expression matching operations.
import re<br>email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'<br>text = "Contact me at [email protected]."<br>matches = re.findall(email_pattern, text)<br>print(matches)math module : Contains mathematical functions. import math<br>print(math.pi) collections module : Offers specialized container datatypes.
from collections import Counter<br>words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']<br>word_counts = Counter(words)<br>print(word_counts)urllib module : Supports fetching URLs (network data requests).
from urllib.request import urlopen<br>url = 'http://www.example.com'<br>response = urlopen(url)<br>html = response.read().decode()<br>print(html[:100])random module : Used to generate random numbers.
import random<br>random_float = random.random()<br>print(random_float)logging module : Provides a flexible logging system.
import logging<br>logging.basicConfig(filename='app.log', level=logging.INFO)<br>logging.info('This is an info message.')Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
