Introduction to Common Python Standard Library Modules
This article introduces several essential Python standard library modules—including os, sys, datetime, math, random, json, re, sqlite3, argparse, logging, and collections—providing brief descriptions and example code snippets that demonstrate their basic usage for file handling, system information, date-time operations, mathematics, randomness, data serialization, regular expressions, database interaction, command-line parsing, logging, and advanced data structures.
os – provides a way to use operating system functionality such as reading/writing files, directory operations, etc.
import os
print(os.getcwd()) # 获取当前工作目录sys – accesses variables and functions closely related to the Python interpreter.
import sys
print(sys.version) # 打印Python版本信息datetime – handles dates and times.
from datetime import datetime
print(datetime.now()) # 当前日期和时间math – provides support for mathematical operations, from basic numeric handling to advanced functions.
import math
print(math.pi) # 圆周率πrandom – generates random numbers.
import random
print(random.randint(1, 10)) # 随机整数json – encodes and decodes JSON data.
import json
data = {'key': 'value'}
json_str = json.dumps(data)
print(json_str) # JSON字符串re – regular expression operations, supporting complex string search and replace.
import re
result = re.search('world', 'Hello world!')
if result:
print("找到匹配:", result.group())sqlite3 – used to interact with SQLite databases.
import sqlite3
conn = sqlite3.connect(':memory:')
print("内存数据库已创建")argparse – used to write user‑friendly command‑line interfaces; it can automatically generate help and usage information and parse command‑line arguments.
import argparse
parser = argparse.ArgumentParser(description='命令行示例')
parser.add_argument('--name', type=str, help='你的名字')
args = parser.parse_args()
print(f"你好, {args.name}")logging – supports a flexible logging system, allowing you to record information during program execution.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("这是一个日志信息")collections – provides additional data structures such as namedtuple, deque, Counter, etc.
from collections import Counter
count = Counter(['a', 'b', 'a', 'c'])
print(count) # 统计元素出现次数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.