
Python标准库提供了丰富的模块,帮助开发者高效处理各种编程任务。本文将介绍20个最常用的标准模块,包括它们的用途、使用方法和代码示例。
re — 正则表达式 用途:在字符串内执行高级搜索、替换与分割,轻松应对复杂文本模式。
importre
text = "Python 3.10 was released on October 4, 2021"
# 查找版本号
match = re.search(r"\d+\.\d+", text)
print(match.group()) # 3.10
# 替换年份
new_text = re.sub(r"\d{4}", "2025", text)
print(new_text) # Python 3.10 was released on October 4, 2025json — JSON 数据编解码 用途:在 Python 对象与 JSON 文本之间高效序列化与反序列化。
importjson
data = {"name": "Alice", "age": 25, "skills": ["Python", "SQL"]}
# Python -> JSON
json_str = json.dumps(data, indent=2)
print(json_str)
# {
# "name": "Alice",
# "age": 25,
# "skills": [
# "Python",
# "SQL"
# ]
# }
# JSON -> Python
parsed = json.loads(json_str)
print(parsed["name"]) # Aliceos — 操作系统交互 用途:跨平台地操作文件、目录、环境变量,是自动化脚本的基础。
importos
print(os.getcwd()) # /Users/yourname/project
os.makedirs("demo_dir", exist_ok=True)
print(os.listdir(".")) # ['demo_dir', ...]
full_path = os.path.join("demo_dir", "file.txt")
print(full_path) # demo_dir/file.txtsys — 解释器相关功能 用途:获取或修改 Python 解释器的行为,例如命令行参数、模块路径。
importsys
print(sys.argv) # ['demo.py']
print(sys.version_info) # sys.version_info(major=3, minor=11, ...)
sys.path.append("/custom/path")
print("/custom/path"insys.path) # Truedatetime — 日期与时间 用途:精准计算时间差、格式化输出、解析字符串,日志与调度必备。
fromdatetimeimportdatetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M")) # 2025-08-19 14:23
tomorrow = now+timedelta(days=1)
print(tomorrow.date()) # 2025-08-20
date_obj = datetime.strptime("2025-12-31", "%Y-%m-%d")
print(date_obj) # 2025-12-31 00:00:00math — 数学运算 用途:提供高精度浮点函数与常量,满足科学计算需求。
importmath
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.sin(math.pi/2)) # 1.0
print(math.factorial(5)) # 120random — 随机数生成 用途:生成伪随机整数、浮点数或抽样,支持洗牌与加权选择。
importrandom
print(random.randint(1, 100)) # 42
print(random.random()) # 0.374540...
colors = ["red", "green", "blue"]
print(random.choice(colors)) # green
random.shuffle(colors)
print(colors) # ['blue', 'red', 'green']collections — 高级容器 用途:用更智能的数据结构(计数器、默认字典、命名元组)简化代码。
fromcollectionsimportCounter, defaultdict, namedtuple
# 计数
words = ["apple", "banana", "apple"]
print(Counter(words).most_common(1)) # [('apple', 2)]
# 默认字典
dd = defaultdict(int)
dd["x"] += 1
print(dd["x"]) # 1
# 命名元组
Point = namedtuple("Point", "x y")
p = Point(10, 20)
print(p.x, p.y) # 10 20itertools — 迭代器工具 用途:无限序列、排列组合、高效循环,减少显式循环。
importitertoolsasit
cnt = it.count(start=10, step=2)
print(next(cnt), next(cnt)) # 10 12
print(list(it.permutations("abc", 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]logging — 日志记录 用途:以分级、格式化方式记录程序运行信息,方便调试与运维。
importlogging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("Service started")
logging.error("Disk full!")2025-08-19 14:23:45,123 - INFO - Service started
2025-08-19 14:23:45,124 - ERROR - Disk full!threading — 多线程 用途:在单进程内并发执行 I/O 密集型任务,提高响应速度。
importthreading, time
defjob(n):
print(f"Thread {n} start")
time.sleep(0.5)
print(f"Thread {n} end")
threads = [threading.Thread(target=job, args=(i,)) foriinrange(3)]
[t.start() fortinthreads]
[t.join() fortinthreads]
print("All threads done")Thread 0 start
Thread 1 start
Thread 2 start
Thread 0 end
Thread 1 end
Thread 2 end
All threads donemultiprocessing — 多进程 用途:利用多核 CPU并行计算,适合 CPU 密集型任务。
frommultiprocessingimportProcess
defsquare(x):
print(f"{x}² = {x * x}")
if__name__ == "__main__":
ps = [Process(target=square, args=(i,)) foriinrange(3)]
[p.start() forpinps]
[p.join() forpinps]0² = 0
1² = 1
2² = 4urllib — URL 处理 用途:下载网络资源、构造查询串、解析网址。
fromurllib.requestimporturlopen
fromurllib.parseimporturlencode, urlparse
# 获取首页前 100 字节
withurlopen("https://www.python.org") asresp:
print(resp.read(100))
# b'<!doctype html>\n<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->\n<!--[if '
# 解析 URL
parts = urlparse("https://docs.python.org/3/")
print(parts.netloc) # docs.python.org
# 构造查询串
print(urlencode({"q": "urllib", "page": 2})) # q=urllib&page=2shutil — 高级文件操作 用途:复制、移动、删除整个目录树,跨平台备份利器。
importshutil, tempfile, os
# 临时目录演示
withtempfile.TemporaryDirectory() astmp:
src = os.path.join(tmp, "src.txt")
dst = os.path.join(tmp, "dst.txt")
withopen(src, "w") asf:
f.write("hello")
shutil.copy(src, dst)
print(os.listdir(tmp)) # ['src.txt', 'dst.txt']csv — CSV 文件处理 用途:读写逗号分隔文件,无缝对接 Excel 与数据库。
importcsv, tempfile, os
withtempfile.NamedTemporaryFile(mode="w+", newline="", delete=False) asf:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerows([["Alice", 25], ["Bob", 30]])
f.seek(0)
forrowincsv.reader(f):
print(row)
os.unlink(f.name)['Name', 'Age']
['Alice', '25']
['Bob', '30']time — 时间相关功能 用途:获取时间戳、睡眠暂停、字符串格式化。
importtime
print(time.time()) # 1724060625.123456
print(time.strftime("%H:%M", time.localtime())) # 14:23
time.sleep(0.2)
print("0.2 s later")0.2 s laterfunctools — 高阶函数 用途:函数装饰与增强,如缓存、偏函数、比较器。
fromfunctoolsimportlru_cache, partial
# 偏函数
power = lambdabase, exp: base**exp
square = partial(power, exp=2)
print(square(5)) # 25
# 缓存
@lru_cache(maxsize=None)
deffib(n):
returnnifn<2elsefib(n-1) +fib(n-2)
print(fib(10)) # 55glob — 文件路径匹配 用途:通配符批量查找文件,支持递归。
importglob, tempfile, os
withtempfile.TemporaryDirectory() astmp:
open(os.path.join(tmp, "a.py"), "w").close()
open(os.path.join(tmp, "b.txt"), "w").close()
py_files = glob.glob(os.path.join(tmp, "*.py"))
print(py_files) # ['/tmp/.../a.py']zipfile — ZIP 压缩文件 用途:创建、查看、解压 ZIP 档案,无需外部工具。
importzipfile, tempfile, os
withtempfile.TemporaryDirectory() astmp:
zip_path = os.path.join(tmp, "demo.zip")
withzipfile.ZipFile(zip_path, "w") aszf:
zf.writestr("hello.txt", "Hi")
withzipfile.ZipFile(zip_path, "r") aszf:
print(zf.namelist()) # ['hello.txt']
zf.extractall(os.path.join(tmp, "out"))
print(os.listdir(os.path.join(tmp, "out"))) # ['hello.txt']argparse — 命令行参数解析 用途:自动生成帮助信息的命令行接口,提升脚本可用性。
importargparse
parser = argparse.ArgumentParser(description="Sum or max some integers.")
parser.add_argument("nums", type=int, nargs="+", help="integers to process")
parser.add_argument("--sum", dest="op", action="store_const",
const=sum, default=max, help="sum the integers")
args = parser.parse_args(["1", "2", "3", "--sum"])
print(args.op(args.nums)) # 6Python的标准库模块涵盖了广泛的功能领域,从文件操作到网络请求,从数据处理到并发编程。掌握这些模块的使用可以大大提高开发效率和代码质量。
“无他,惟手熟尔”!有需要的用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!😊
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!