Skip to content

第 10 章 · 标准库速览:能少写就少写 ​

本章目标 ​

认识日常最常用的标准库,遇到任务时先想"标准库有没有现成的"。

Python 的哲学是"自带电池"(batteries included):装完 Python,就已经有几百个库可以用。

10.1 文件与目录 ​

python
from pathlib import Path

p = Path("E:/data/report.txt")
print(p.name)             # report.txt
print(p.stem, p.suffix)   # report  .txt
print(p.parent)           # E:/data
print(p.exists(), p.is_file(), p.is_dir())
print(p.stat().st_size)   # 字节数

# 遍历目录里所有 txt
for f in Path(".").glob("*.txt"):
    print(f.name)

# 递归遍历
for f in Path(".").rglob("*.py"):
    print(f)

# 新建/改名/删除
Path("out").mkdir(parents=True, exist_ok=True)
# p.rename("new.txt")
# p.unlink()            # 删除文件(谨慎)
python
import os, shutil, glob

print(os.getcwd())              # 当前工作目录
print(os.listdir("."))          # 列目录
shutil.copy("a.txt", "b.txt")   # 复制
shutil.move("b.txt", "out/")    # 移动
print(glob.glob("**/*.md", recursive=True))

10.2 文本处理与正则 ​

python
import re

text = "订单 A123 金额 88 元,订单 B456 金额 199 元"

print(re.findall(r"[A-Z]\d{3}", text))        # ['A123', 'B456']
print(re.findall(r"\d+", text))               # ['123', '88', '456', '199']

for m in re.finditer(r"金额 (\d+)", text):
    print(m.group(1))                         # 88  199

print(re.sub(r"\d+", "#", text))              # 把数字都换成 #

常用元字符:\d 数字、\w 字母数字下划线、\s 空白、. 任意、* + ? {n,m} 次数、[] 集合、() 分组、^ $ 行首行尾。

写正则会晕是正常的。技巧:先在小样本上 findall 试,慢慢加条件。

10.3 数学、随机与统计 ​

python
import math, random, statistics

print(math.sqrt(2), math.floor(2.9), math.ceil(2.1))
print(math.log10(1000))               # 3.0

random.seed(42)                       # 固定种子,结果可复现
print(random.random())                # 0~1 小数
print(random.uniform(1, 10))          # 区间小数
print(random.choice(["A", "B", "C"]))
print(random.sample(range(1, 50), 6)) # 抽 6 个不重复(模拟彩票)

data = [12, 15, 18, 20, 22]
print(statistics.mean(data))          # 17
print(statistics.median(data))        # 18
print(statistics.stdev(data))         # 标准差

10.4 日期与时间 ​

python
from datetime import datetime, date, timedelta

now = datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute)
print(now.strftime("%Y-%m-%d %A"))            # 2026-09-18 Friday

today = date.today()
print((today + timedelta(days=7)).isoformat())    # 一周后

d = datetime.strptime("2026-09-18 09:30", "%Y-%m-%d %H:%M")
print((now - d).days)

做股票/交易类程序时,日期差、交易日计算最常用 timedelta。

10.5 数据格式 ​

python
import json, csv
from decimal import Decimal

# 精确小数(算钱必用)
print(Decimal("0.1") + Decimal("0.2"))    # 0.3

# JSON 已在第 07 章讲过
# CSV 用 DictReader/DictWriter 更方便
with open("scores.csv", encoding="utf-8-sig") as f:
    for row in csv.DictReader(f):
        print(row["姓名"], row["成绩"])

10.6 集合与算法工具箱 ​

python
from collections import Counter, defaultdict, namedtuple, deque
from itertools import combinations, permutations, groupby, chain

print(Counter("mississippi").most_common(3))

Point = namedtuple("Point", "x y")        # 轻量"类"
p = Point(1, 2)
print(p.x, p.y)

print(list(permutations([1, 2, 3], 2)))   # 排列
print(list(chain([1, 2], [3, 4])))        # 串成一串

10.7 系统、压缩、编码、ID ​

python
import sys, subprocess, zipfile, hashlib, uuid

print(sys.version, sys.platform)
# subprocess.run(["dir"], shell=True)     # 调外部命令(Windows 用 dir)

with zipfile.ZipFile("out.zip", "w") as z:
    z.write("a.txt")

print(hashlib.md5(b"hello").hexdigest())  # 校验文件常用
print(uuid.uuid4())                       # 唯一 ID

10.8 网络访问(标准库自带) ​

python
from urllib.request import urlopen
import json

with urlopen("https://httpbin.org/get", timeout=10) as resp:
    data = json.load(resp)

print(data["url"])

实际项目里更推荐第三方库 requests(第 11 章),代码更短、功能更全;urllib 适合"不想装任何库"的场合。

10.9 性能与质量 ​

python
import time, timeit, logging

t0 = time.perf_counter()
sum(range(100000))
print(f"{(time.perf_counter() - t0) * 1000:.2f} ms")

print(timeit.timeit("'-'.join(['a','b'])", number=1000))   # 快速测速

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.info("这是正经日志,比 print 强")     # 能分级、能写文件、能带时间

10.10 多线程与并发(了解,别急着用) ​

python
from concurrent.futures import ThreadPoolExecutor

def work(n):
    return n * n

with ThreadPoolExecutor(max_workers=4) as ex:
    print(list(ex.map(work, range(5))))      # [0, 1, 4, 9, 16]

小提示:Python 有 GIL,计算密集型任务多线程不会变快,IO 密集(下网页、读文件)才有用;真要多核跑计算用 multiprocessing。

10.11 遇到任务先问一句:"标准库有吗?" ​

想做的事用什么
处理路径/遍历文件pathlib、glob
匹配/替换文本re
存配置、存数据json、csv、sqlite3
算钱decimal
时间日期datetime、time
计数/分组/队列collections
组合排列/迭代技巧itertools
跑外部命令subprocess
访问网页/API(不想装库)urllib.request
发邮件smtplib + email
压缩包zipfile、tarfile、gzip
哈希/唯一 IDhashlib、uuid
日志logging
命令行参数argparse
测速timeit

10.12 练一练 ​

  1. 用 pathlib 统计当前目录下 .py 文件的数量和总大小,打印出来。
  2. 用 re 从一段文本里提取所有日期(形如 2026-09-18)和金额。
  3. 用 Counter 统计一句话里出现最多的 3 个字(去掉标点)。
  4. 用 datetime 计算"距离 2027-01-01 还有多少天"。

本章关键词 ​

pathlib、glob、re、math / random / statistics、datetime、decimal、collections、itertools、subprocess、logging

试图用自己的方式,重新定义属于我的人生