Using Built-in Python Modules
Table of Contents
1. [Introduction to Built-in Modules](#introduction) 2. [Module Import Mechanisms](#import-mechanisms) 3. [Essential Built-in Modules](#essential-modules) 4. [File and Directory Operations](#file-operations) 5. [Date and Time Handling](#datetime-operations) 6. [Mathematical Operations](#math-operations) 7. [System and Operating System Interface](#system-operations) 8. [Data Serialization](#data-serialization) 9. [Regular Expressions](#regex-operations) 10. [Networking and URLs](#networking) 11. [Best Practices](#best-practices)Introduction to Built-in Modules {#introduction}
Built-in Python modules are pre-installed libraries that come with every Python installation. These modules provide essential functionality for common programming tasks without requiring external dependencies. They are part of Python's standard library and offer robust, tested solutions for various operations.
Benefits of Using Built-in Modules
| Benefit | Description | |---------|-------------| | No Installation Required | Available immediately with Python installation | | Optimized Performance | Written in C and optimized for speed | | Stability | Thoroughly tested and maintained by Python core team | | Cross-platform | Work consistently across different operating systems | | Documentation | Comprehensive official documentation available |
Module Import Mechanisms {#import-mechanisms}
Python provides several ways to import modules, each with specific use cases and implications.
Import Statement Variations
`python
Standard import
import os import sys import mathImport specific functions/classes
from datetime import datetime, timedelta from collections import defaultdict, CounterImport with alias
import numpy as np # External module example import pandas as pd # External module exampleImport all (not recommended for most cases)
from math import *Conditional imports
try: import json except ImportError: import simplejson as json`Import Statement Types
| Import Type | Syntax | Use Case | Example |
|-------------|--------|----------|---------|
| Module Import | import module | Import entire module | import os |
| Selective Import | from module import item | Import specific items | from os import path |
| Alias Import | import module as alias | Create shorter names | import datetime as dt |
| Multiple Import | import mod1, mod2 | Import multiple modules | import os, sys, math |
Essential Built-in Modules {#essential-modules}
Core System Modules
`python
import sys
import os
import platform
import subprocess
System information
print("Python version:", sys.version) print("Platform:", platform.system()) print("Current working directory:", os.getcwd())Command line arguments
print("Script arguments:", sys.argv)Python path
print("Python path:", sys.path)Environment variables
print("PATH environment:", os.environ.get('PATH'))`Collections Module
The collections module provides specialized container datatypes.
`python
from collections import (
defaultdict, Counter, OrderedDict,
namedtuple, deque, ChainMap
)
defaultdict - provides default values for missing keys
dd = defaultdict(list) dd['key1'].append('value1') dd['key2'].append('value2') print("DefaultDict:", dict(dd))Counter - counts hashable objects
text = "hello world" counter = Counter(text) print("Character count:", counter) print("Most common:", counter.most_common(3))namedtuple - creates tuple subclasses with named fields
Person = namedtuple('Person', ['name', 'age', 'city']) person1 = Person('Alice', 30, 'New York') print(f"Person: {person1.name}, Age: {person1.age}")deque - double-ended queue
queue = deque(['a', 'b', 'c']) queue.appendleft('z') queue.append('d') print("Deque:", queue)OrderedDict - maintains insertion order (Python 3.7+ dict does this too)
od = OrderedDict() od['first'] = 1 od['second'] = 2 od['third'] = 3 print("OrderedDict:", od)`File and Directory Operations {#file-operations}
OS Module Operations
`python
import os
import shutil
import glob
from pathlib import Path
Directory operations
current_dir = os.getcwd() print(f"Current directory: {current_dir}")Create directory
os.makedirs('test_directory/subdirectory', exist_ok=True)List directory contents
contents = os.listdir('.') print("Directory contents:", contents)File operations
file_stats = os.stat('example.txt') if os.path.exists('example.txt') else None if file_stats: print(f"File size: {file_stats.st_size} bytes") print(f"Last modified: {file_stats.st_mtime}")Path operations
file_path = os.path.join('directory', 'subdirectory', 'file.txt') print(f"Joined path: {file_path}") print(f"Directory name: {os.path.dirname(file_path)}") print(f"Base name: {os.path.basename(file_path)}") print(f"Split extension: {os.path.splitext(file_path)}")`Pathlib Module (Modern Approach)
`python
from pathlib import Path
Create Path objects
current_path = Path.cwd() home_path = Path.home()Path operations
file_path = Path('data') / 'files' / 'document.txt' print(f"File path: {file_path}") print(f"Parent directory: {file_path.parent}") print(f"File name: {file_path.name}") print(f"File stem: {file_path.stem}") print(f"File suffix: {file_path.suffix}")File operations
if file_path.exists(): content = file_path.read_text() print(f"File content: {content}")Directory operations
data_dir = Path('data') if data_dir.exists() and data_dir.is_dir(): for file in data_dir.iterdir(): if file.is_file(): print(f"File: {file.name}")Glob patterns
python_files = list(Path('.').glob('*.py')) print(f"Python files: {python_files}")`File Operations Comparison
| Operation | os module | pathlib | Notes |
|-----------|-----------|---------|-------|
| Current Directory | os.getcwd() | Path.cwd() | pathlib returns Path object |
| Join Paths | os.path.join(a, b) | Path(a) / b | pathlib uses / operator |
| Check Existence | os.path.exists(path) | Path(path).exists() | Both return boolean |
| Read File | open(path).read() | Path(path).read_text() | pathlib handles file closing |
| File Stats | os.stat(path) | Path(path).stat() | Similar functionality |
Date and Time Handling {#datetime-operations}
Datetime Module
`python
from datetime import datetime, date, time, timedelta
import calendar
import time as time_module
Current date and time
now = datetime.now() today = date.today() current_time = datetime.now().time()print(f"Current datetime: {now}") print(f"Today's date: {today}") print(f"Current time: {current_time}")
Creating specific dates
specific_date = datetime(2024, 12, 25, 15, 30, 0) date_only = date(2024, 12, 25) time_only = time(15, 30, 0)Formatting dates
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") formatted_date_readable = now.strftime("%B %d, %Y at %I:%M %p")print(f"Formatted date: {formatted_date}") print(f"Readable date: {formatted_date_readable}")
Parsing dates from strings
date_string = "2024-12-25 15:30:00" parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") print(f"Parsed date: {parsed_date}")Date arithmetic
tomorrow = today + timedelta(days=1) last_week = today - timedelta(weeks=1) next_month = today + timedelta(days=30)print(f"Tomorrow: {tomorrow}") print(f"Last week: {last_week}") print(f"Next month: {next_month}")
Time zones (requires pytz for full timezone support)
utc_now = datetime.utcnow() print(f"UTC time: {utc_now}")`Time Module Operations
`python
import time
Current timestamp
timestamp = time.time() print(f"Current timestamp: {timestamp}")Sleep operation
print("Sleeping for 2 seconds...") time.sleep(2) print("Done sleeping")Performance measurement
start_time = time.perf_counter()Some operation here
sum(range(1000000)) end_time = time.perf_counter() execution_time = end_time - start_time print(f"Execution time: {execution_time:.4f} seconds")Time formatting
local_time = time.localtime() formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time) print(f"Formatted local time: {formatted_time}")`Date/Time Format Codes
| Code | Meaning | Example |
|------|---------|---------|
| %Y | Year with century | 2024 |
| %y | Year without century | 24 |
| %m | Month as number | 01-12 |
| %B | Full month name | January |
| %b | Abbreviated month | Jan |
| %d | Day of month | 01-31 |
| %H | Hour (24-hour) | 00-23 |
| %I | Hour (12-hour) | 01-12 |
| %M | Minute | 00-59 |
| %S | Second | 00-59 |
| %p | AM/PM | AM, PM |
Mathematical Operations {#math-operations}
Math Module
`python
import math
import random
import statistics
from decimal import Decimal, getcontext
from fractions import Fraction
Basic mathematical functions
numbers = [1, 4, 9, 16, 25]Math module functions
print(f"Square root of 16: {math.sqrt(16)}") print(f"Ceiling of 4.2: {math.ceil(4.2)}") print(f"Floor of 4.8: {math.floor(4.8)}") print(f"Absolute value of -5: {math.fabs(-5)}")Trigonometric functions
angle = math.pi / 4 # 45 degrees in radians print(f"Sin(45°): {math.sin(angle)}") print(f"Cos(45°): {math.cos(angle)}") print(f"Tan(45°): {math.tan(angle)}")Logarithmic functions
print(f"Natural log of e: {math.log(math.e)}") print(f"Log base 10 of 100: {math.log10(100)}") print(f"Log base 2 of 8: {math.log2(8)}")Power and exponential
print(f"2 to the power of 3: {math.pow(2, 3)}") print(f"e to the power of 2: {math.exp(2)}")Constants
print(f"Pi: {math.pi}") print(f"Euler's number: {math.e}") print(f"Tau (2*pi): {math.tau}")`Random Module
`python
import random
import secrets # For cryptographically secure random numbers
Basic random operations
print(f"Random float [0.0, 1.0): {random.random()}") print(f"Random integer [1, 10]: {random.randint(1, 10)}") print(f"Random choice from list: {random.choice(['apple', 'banana', 'cherry'])}")Random sampling
numbers = list(range(1, 11)) print(f"Random sample of 3: {random.sample(numbers, 3)}")Shuffle list
cards = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'] random.shuffle(cards) print(f"Shuffled cards: {cards[:5]}") # Show first 5Random with different distributions
print(f"Gaussian distribution: {random.gauss(0, 1)}") print(f"Uniform distribution [1, 10]: {random.uniform(1, 10)}")Seed for reproducible results
random.seed(42) print(f"Seeded random: {random.random()}") random.seed(42) print(f"Same seeded random: {random.random()}")Secure random (for cryptographic purposes)
secure_token = secrets.token_hex(16) print(f"Secure token: {secure_token}")`Statistics Module
`python
import statistics
Sample data
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] grades = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91]Measures of central tendency
print(f"Mean: {statistics.mean(data)}") print(f"Median: {statistics.median(data)}") print(f"Mode: {statistics.mode([1, 2, 2, 3, 3, 3])}")Measures of spread
print(f"Standard deviation: {statistics.stdev(grades)}") print(f"Variance: {statistics.variance(grades)}") print(f"Population std dev: {statistics.pstdev(grades)}")Quantiles
print(f"Quartiles: {statistics.quantiles(grades, n=4)}")`System and Operating System Interface {#system-operations}
System Module Operations
`python
import sys
import platform
import subprocess
import psutil # Note: This is not built-in, but commonly used
System information
print(f"Python version: {sys.version}") print(f"Python executable: {sys.executable}") print(f"Platform: {platform.platform()}") print(f"Architecture: {platform.architecture()}") print(f"Processor: {platform.processor()}") print(f"System: {platform.system()}") print(f"Release: {platform.release()}")Memory information
print(f"Memory usage: {sys.getsizeof('Hello World')} bytes")Command line arguments
print(f"Script name: {sys.argv[0]}") print(f"Arguments: {sys.argv[1:]}")Python path
print("Python path directories:") for path in sys.path: print(f" {path}")`Subprocess Module
`python
import subprocess
import shlex
Run simple command
try: result = subprocess.run(['ls', '-l'], capture_output=True, text=True, check=True) print("Command output:") print(result.stdout) except subprocess.CalledProcessError as e: print(f"Command failed with return code {e.returncode}") print(f"Error output: {e.stderr}")Run command with shell
try: result = subprocess.run('echo "Hello from shell"', shell=True, capture_output=True, text=True) print(f"Shell output: {result.stdout.strip()}") except Exception as e: print(f"Shell command failed: {e}")Pipe operations
try: # Equivalent to: ps aux | grep python ps_process = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) grep_process = subprocess.Popen(['grep', 'python'], stdin=ps_process.stdout, stdout=subprocess.PIPE, text=True) ps_process.stdout.close() output, error = grep_process.communicate() print("Piped command output:") print(output) except Exception as e: print(f"Piped command failed: {e}")`Data Serialization {#data-serialization}
JSON Module
`python
import json
from datetime import datetime
Sample data
data = { 'name': 'John Doe', 'age': 30, 'city': 'New York', 'hobbies': ['reading', 'swimming', 'coding'], 'married': True, 'children': None, 'address': { 'street': '123 Main St', 'zipcode': '10001' } }Serialize to JSON string
json_string = json.dumps(data, indent=2) print("JSON string:") print(json_string)Serialize to file
with open('data.json', 'w') as f: json.dump(data, f, indent=2)Deserialize from JSON string
parsed_data = json.loads(json_string) print(f"Parsed data type: {type(parsed_data)}") print(f"Name: {parsed_data['name']}")Deserialize from file
with open('data.json', 'r') as f: loaded_data = json.load(f) print(f"Loaded from file: {loaded_data['city']}")Custom JSON encoder for datetime
class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj)Data with datetime
datetime_data = { 'timestamp': datetime.now(), 'event': 'user_login' }json_with_datetime = json.dumps(datetime_data, cls=DateTimeEncoder, indent=2)
print("JSON with datetime:")
print(json_with_datetime)
`
Pickle Module
`python
import pickle
import base64
Sample complex data structure
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person('{self.name}', {self.age})"Create complex data
complex_data = { 'person': Person('Alice', 25), 'numbers': [1, 2, 3, 4, 5], 'nested': {'a': {'b': {'c': 'deep_value'}}} }Serialize with pickle
pickled_data = pickle.dumps(complex_data) print(f"Pickled data size: {len(pickled_data)} bytes")Deserialize with pickle
unpickled_data = pickle.loads(pickled_data) print(f"Unpickled person: {unpickled_data['person']}") print(f"Unpickled nested value: {unpickled_data['nested']['a']['b']['c']}")Pickle to/from file
with open('data.pickle', 'wb') as f: pickle.dump(complex_data, f)with open('data.pickle', 'rb') as f: loaded_pickle_data = pickle.load(f) print(f"Loaded from pickle file: {loaded_pickle_data['person']}")
Base64 encoding for text representation
encoded_pickle = base64.b64encode(pickled_data).decode('ascii') print(f"Base64 encoded pickle: {encoded_pickle[:50]}...")`Serialization Comparison
| Format | Module | Pros | Cons | Use Case | |--------|--------|------|------|----------| | JSON | json | Human readable, cross-language | Limited data types | APIs, config files | | Pickle | pickle | All Python objects | Python-only, security risks | Python-to-Python data | | CSV | csv | Simple, spreadsheet compatible | Flat data only | Tabular data | | XML | xml | Structured, self-documenting | Verbose | Document markup |
Regular Expressions {#regex-operations}
RE Module
`python
import re