Fundamentals 8 min read

Top 20 Most Common Python Standard Library Modules

This article introduces the twenty most frequently used Python standard library modules, such as os, sys, math, random, datetime, json, re, collections, itertools, argparse, and others, explaining their core functionalities and providing concise code examples to help developers efficiently manage files, data, networking, and more.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Top 20 Most Common Python Standard Library Modules

Python's standard library is a collection of modules that come with the Python installation, covering file operations, system interaction, data processing, network programming, and many other functionalities. Mastering these built‑in modules can greatly improve development efficiency and avoid reinventing the wheel.

1. os — Operating system interaction

The os module provides functions for interacting with the operating system, such as file/directory management, reading environment variables, etc.

import os

# Get current working directory
print(os.getcwd())

# List directory contents
print(os.listdir('.'))

# Create / delete a directory
os.mkdir("test_dir")
os.rmdir("test_dir")

2. sys — System-specific parameters

The sys module gives access to variables and functions used by the Python interpreter, such as command‑line arguments and module search paths.

import sys

# Get command‑line arguments
print(sys.argv)

# Show Python path
print(sys.path)

# Exit program
sys.exit(0)

3. math — Mathematical operations

The math module provides mathematical functions such as trigonometric functions, logarithms, and power operations.

import math

print(math.sqrt(16))   # 4.0
print(math.sin(math.pi / 2))   # 1.0
print(math.factorial(5))   # 120

4. random — Random number generation

The random module is used to generate random numbers, make random selections, etc.

import random

# Generate a random integer
print(random.randint(1, 10))

# Randomly choose an element from a list
print(random.choice(["A", "B", "C"]))

# Shuffle a list
lst = [1, 2, 3]
random.shuffle(lst)
print(lst)

5. datetime — Date and time handling

The datetime module handles dates, times, and time differences.

from datetime import datetime, timedelta

# Current time
now = datetime.now()
print(now)

# Add one day
tomorrow = now + timedelta(days=1)
print(tomorrow)

# Format time
print(now.strftime("%Y-%m-%d %H:%M:%S"))

6. json — JSON data processing

The json module parses and generates JSON data.

import json

data = {"name": "Alice", "age": 25}

# Convert to JSON string
json_str = json.dumps(data)
print(json_str)

# Parse JSON string
parsed_data = json.loads(json_str)
print(parsed_data["name"])  # Alice

7. re — Regular expressions

The re module provides regex matching for searching, replacing, and other string operations.

import re

text = "Python 3.10 released in 2021"

# Find all numbers
matches = re.findall(r'\d+', text)
print(matches)  # ['3', '10', '2021']

# Replace numbers with X
new_text = re.sub(r'\d+', 'X', text)
print(new_text)  # "Python X.X released in X"

8. collections — Advanced data structures

The collections module offers more powerful containers such as defaultdict and Counter .

from collections import defaultdict, Counter

# defaultdict automatically initializes missing keys
dd = defaultdict(int)
dd["a"] += 1
print(dd["a"])  # 1

# Counter counts element occurrences
cnt = Counter("hello")
print(cnt)  # Counter({'h': 1, 'e': 1, 'l': 2, 'o': 1})

9. itertools — Iteration utilities

The itertools module provides efficient iterator tools such as permutations, combinations, and infinite iterators.

from itertools import permutations, cycle

# Permutations of length 2
print(list(permutations("ABC", 2)))  # [('A', 'B'), ('A', 'C'), ('B', 'A'), ...]

# Infinite cycle
for i in cycle([1, 2, 3]):
    if i > 5:
        break
    print(i)  # 1, 2, 3, 1, 2, 3, ...

10. argparse — Command‑line argument parsing

The argparse module parses command‑line arguments, commonly used in script development.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", help="Your name")
args = parser.parse_args()

if args.name:
    print(f"Hello, {args.name}!")

11‑20. Other commonly used modules

Module

Purpose

csv

Read/write CSV files

logging

Logging

hashlib

Hash encryption (MD5, SHA256)

urllib

HTTP requests

subprocess

Run system commands

zipfile

Compress/decompress ZIP files

sqlite3

SQLite database operations

threading

Multithreaded programming

multiprocessing

Multiprocess programming

unittest

Unit testing

Conclusion

The Python standard library is powerful; mastering these modules can significantly boost development efficiency. This article presented 20 of the most common standard library modules, covering file handling, data processing, network requests, multithreading, and more. Practice using these tools in real projects to reduce redundant code and improve code quality.

Pythonprogrammingcode examplesfundamentalsModulesstandard-library
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.