Python 标准库详解

Python 标准库字典:按模块分条,每条给定位、核心 API、示例与坑。覆盖日常工程 90% 的场景。

1. pathlib – 现代路径操作

描述

面向对象的路径 API,取代 os.path。Path 拼接用 / 运算符,读写一行搞定。

语法和示例

from pathlib import Path
p = Path('data') / 'a.txt'
p.exists(); p.is_file(); p.suffix; p.stem; p.name
p.parent.mkdir(parents=True, exist_ok=True)
p.read_text(encoding='utf-8')
p.write_text('hi', encoding='utf-8')
list(p.parent.glob('*.log'))
list(Path('.').rglob('*.py'))            # 递归
p.with_suffix('.md'); p.resolve()

注意事项

  • read_text/write_text 默认编码是系统 locale,中文场景必须显式 encoding=’utf-8′
  • glob 返回生成器,要多次用先 list
  • resolve() 会跟随符号链接,strict=True 时路径不存在抛错
  • 旧代码 os.path 可继续用,但新代码统一 pathlib 更好

2. os / shutil – 系统与文件操作

描述

os 环境变量与进程;shutil 高级文件操作(复制树/移动/磁盘用量)。

语法和示例

import os, shutil
os.environ.get('HOME'); os.getenv('X', 'default')
os.path.join('a','b'); os.path.exists(p)
os.listdir('.'); os.walk('.')
shutil.copy(src, dst); shutil.copy2(src, dst)
shutil.copytree('a', 'b', dirs_exist_ok=True)
shutil.rmtree('dir'); shutil.move(a, b)
shutil.disk_usage('/'); shutil.which('git')

注意事项

  • os.walk 是生成器,遍历大目录很慢——用 scandir 或 pathlib
  • copytree 默认目标必须不存在,3.8+ 才有 dirs_exist_ok
  • rmtree 不可恢复,删前确认路径
  • os.environ 修改只影响当前进程与子进程

3. tempfile – 临时文件与目录

描述

安全创建临时资源。NamedTemporaryFile 用完自动删(Windows 有坑)。

语法和示例

import tempfile
with tempfile.NamedTemporaryFile(suffix='.txt', delete=True) as f:
    f.write(b'x'); f.flush(); f.seek(0); f.read()
with tempfile.TemporaryDirectory() as d:
    p = Path(d) / 'a.txt'

注意事项

  • Windows 上 NamedTemporaryFile 打开时无法被其他进程访问——需 delete=False 后手动删
  • flush 后才能读到刚写的字节
  • TemporaryDirectory 退出时整目录删除,别把重要文件放进去

4. json – JSON 编解码

描述

标准 JSON 库。注意键必须是 str,datetime 需自定义 default。

语法和示例

import json
json.dumps(obj, ensure_ascii=False, indent=2)
json.loads(text)
json.dumps(obj, default=str)             # 无法序列化时降级为字符串
json.JSONEncoder(indent=2)               # 定制编码器
json.load(open('a.json', encoding='utf-8'))

1. 读写文件
with open('a.json', encoding='utf-8') as f:
    data = json.load(f)
with open('b.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

1. 处理 datetime / Decimal / set
class Enc(json.JSONEncoder):
    def default(self, o):
        from datetime import datetime
        if isinstance(o, datetime): return o.isoformat()
        if isinstance(o, set): return list(o)
        return super().default(o)
json.dumps({'t': datetime.now()}, cls=Enc)

1. 大整数保留精度
json.loads('{"n": 123456789012345678901}', parse_int=str)

注意事项

  • ensure_ascii=False 才输出中文原文,否则是 \uXXXX
  • json 的键必须是 str(int 键会被转成字符串)
  • JSON 不支持 datetime/Decimal/set,需 default= 处理
  • 载入大 JSON 会占大量内存——流式用 ijson 库

5. csv – CSV 读写

描述

用 csv 模块而非手写 split,能正确处理引号、换行、转义。

语法和示例

import csv
with open('x.csv', newline='', encoding='utf-8') as f:
    rows = list(csv.DictReader(f))
with open('out.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=['a','b'])
    w.writeheader(); w.writerows(data)

1. 追加写入
with open('log.csv', 'a', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['ts', 'msg'])

1. 自定义分隔符(TSV)
csv.reader(f, delimiter='\t')

1. 读取时不猜类型(全字符串)
rows = list(csv.reader(f))
typed = [{'id': int(r[0]), 'name': r[1]} for r in rows[1:]]

注意事项

  • open 必须传 newline=”,否则 Windows 上会出现空行
  • 手写 split(‘,’) 会破坏含逗号/引号的字段
  • DictReader 的首行默认当表头,无表头用 fieldnames= 指定

6. datetime – 日期时间

描述

四大类型:date/time/datetime(无时区)、带 tzinfo 的 aware datetime、timedelta。

语法和示例

from datetime import datetime, date, timedelta, timezone
datetime.now(); datetime.now(timezone.utc)
dt = datetime(2026, 10, 30, 10, 0)
dt.strftime('%Y-%m-%d %H:%M')
datetime.strptime('2026-10-30', '%Y-%m-%d')
dt + timedelta(days=7)
(a - b).total_seconds()
dt.replace(tzinfo=timezone.utc)
dt.isoformat()

注意事项

  • naive datetime 无时区,跨时区比较会错——存库/传输一律用 aware 或 UTC
  • strptime 的格式必须与字符串严格匹配,否则 ValueError
  • datetime 是不可变的,加减返回新对象
  • ISO 格式用 isoformat() 而非手拼字符串

7. zoneinfo – IANA 时区(3.9+)

描述

标准库时区实现,取代 pytz。Windows 需额外装 tzdata 包。

语法和示例

from zoneinfo import ZoneInfo
dt = datetime(2026, 10, 30, 10, tzinfo=ZoneInfo('Asia/Shanghai'))
dt.astimezone(ZoneInfo('UTC'))
tz = ZoneInfo('Asia/Shanghai'); tz.key

注意事项

  • Windows 上 zoneinfo 需要 pip install tzdata
  • ZoneInfo 对象要缓存(构造有开销),别在循环里每次 new
  • 别再用 pytz 的 localize 模式,zoneinfo 直接 tzinfo= 即可

8. collections – 专用容器

描述

Counter 计数、defaultdict 缺省工厂、deque 双端队列、namedtuple 具名元组、OrderedDict(3.7 后普通 dict 已有序)。

语法和示例

from collections import Counter, defaultdict, deque, namedtuple
Counter('banana').most_common(2)
d = defaultdict(list); d['k'].append(1)
dq = deque([1,2], maxlen=3); dq.appendleft(0); dq.pop()
P = namedtuple('P', 'x y'); P(1,2)._replace(x=9)
Counter(a) + Counter(b); Counter(a) - Counter(b)

注意事项

  • defaultdict 访问未存在的键会自动创建(哪怕只是读取)——易造成意外写入
  • deque 的 maxlen 满了会自动丢弃另一端,注意数据丢失
  • Counter 的算术运算会丢弃非正值计数

9. itertools – 迭代器组合

描述

排列组合、无限序列、分组、分批。全部惰性。

语法和示例

import itertools as it
it.chain(a, b); it.chain.from_iterable(nested)
it.combinations('abc', 2); it.permutations('ab')
it.product('AB', repeat=2)
it.groupby(sorted(xs, key=k), key=k)     # 必须先排序!
it.islice(it.count(10), 5)
it.pairwise([1,2,3])                     # (1,2) (2,3)(3.10+)
it.batched(xs, 100)                      # 定长分批(3.12+)
it.accumulate([1,2,3])                   # 前缀和

注意事项

  • groupby 只合并相邻元素——不先排序会得到多组相同键
  • 无限迭代器(count/cycle/repeat)必须配 islice 或 break
  • combinations/permutations 结果数量爆炸,大 n 慎用

10. functools – 高阶函数工具

描述

lru_cache 缓存、partial 预绑定、reduce 归约、wraps 装饰器元信息、total_ordering。

语法和示例

from functools import lru_cache, cache, partial, reduce, wraps
@cache                                   # 3.9+ 无长度限制
def f(n): ...
add2 = partial(pow, exp=2)
reduce(lambda a,b: a+b, xs, 0)
@wraps(fn)  # 装饰器内使用

注意事项

  • lru_cache/cache 的参数必须可哈希
  • 缓存会持引用导致内存不释放——长生命周期函数慎用 maxsize=None
  • reduce 在 Python 3 移入 functools(不再是内置)

11. subprocess – 子进程

描述

run 是首选(阻塞返回 CompletedProcess);Popen 流式;check=True 非零退出抛异常。

语法和示例

import subprocess
r = subprocess.run(['git','status'], capture_output=True, text=True, check=True)
r.returncode; r.stdout; r.stderr
subprocess.run('echo hi', shell=True)     # 经 shell(注入风险)
p = subprocess.Popen(['ping','-c','4',h], stdout=subprocess.PIPE)
p.communicate()

注意事项

  • 默认 shell=False,传列表更安全;shell=True + 用户输入 = 命令注入
  • capture_output=True 才拿到 stdout/stderr
  • text=True(或 encoding=’utf-8’)才返回 str 而非 bytes
  • 管道输出不读完可能阻塞——用 communicate() 而非 wait()

12. threading / multiprocessing – 并发

描述

threading 受 GIL 限制(IO 密集有效);multiprocessing 真并行(CPU 密集)。

语法和示例

import threading, multiprocessing as mp
with concurrent.futures.ThreadPoolExecutor(8) as ex:
    list(ex.map(fetch, urls))
with concurrent.futures.ProcessPoolExecutor() as ex:
    list(ex.map(cpu_task, data))
t = threading.Thread(target=work, daemon=True); t.start(); t.join()
mp.Queue(); mp.Pool(4)

注意事项

  • GIL 下多线程不能加速 CPU 密集,只能加速 IO 等待
  • multiprocessing 的对象必须可 pickle——不能传 lambda/打开的文件
  • Windows 上 multiprocessing 需 if __name__ == ‘__main__’ 保护
  • 进程池创建开销大,任务太细碎反而更慢

13. asyncio – 异步 IO

描述

事件循环 + 协程。gather 并发、TaskGroup(3.11+)结构化、timeout(3.11+)。

语法和示例

import asyncio
async def main():
    rs = await asyncio.gather(*(fetch(u) for u in urls), return_exceptions=True)
    async with asyncio.TaskGroup() as tg:
        tg.create_task(fetch(u))
    async with asyncio.timeout(5): await slow()
asyncio.run(main())

注意事项

  • asyncio.run 不能在已有循环内调用(Jupyter 里要 await 直接跑或 nest_asyncio)
  • 协程里用 requests/time.sleep 会阻塞整个循环——用 aiohttp/asyncio.sleep
  • gather 默认一个异常就整体抛出(return_exceptions=True 才各自返回)
  • TaskGroup 相比 gather 有更好的取消与异常聚合语义

14. logging – 日志

描述

分级日志 + Handler + Formatter。生产用 RotatingFileHandler 防磁盘写满。

语法和示例

import logging
logging.basicConfig(level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)s %(message)s')
log = logging.getLogger(__name__)
log.info('user %s login', uid)            # 惰性格式化(推荐)
from logging.handlers import RotatingFileHandler
h = RotatingFileHandler('app.log', maxBytes=10*1024*1024, backupCount=5)

1. 分模块 logger + 文件轮转
log = logging.getLogger('app.io')
h = RotatingFileHandler('app.log', maxBytes=10_000_000, backupCount=5)
h.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s %(name)s %(message)s'))
log.addHandler(h); log.setLevel(logging.INFO)

1. 异常堆栈
try:
    risky()
except Exception:
    log.exception('处理失败')      # 自动带堆栈

注意事项

  • 用 %s 占位而非 f-string —— 日志被过滤时省掉字符串拼接开销
  • basicConfig 只生效一次,重复调用无效果
  • 异常日志要传 exc_info=True 或 log.exception,否则丢堆栈
  • 库代码不要配置 root logger,用 getLogger(__name__)

15. re – 正则表达式

描述

compile 预编译复用;match 从头匹配、search 任意位置、findall 全部、sub 替换。

语法和示例

import re
p = re.compile(r'(\d{4})-(\d{2})')
p.search('2026-10')                      # 匹配对象或 None
p.findall('2026-10 2027-01')
re.sub(r'\d', '#', 'a1b2')
re.split(r'[,;]+', 'a,b;c')
m.group(0), m.group(1), m.groups()
re.compile(r'\d+', re.MULTILINE | re.DOTALL)

1. 命名分组(取值更清晰)
m = re.match(r'(?P<year>\d{4})-(?P<mon>\d{2})', '2026-10')
m.group('year'), m.groupdict()

1. 替换用函数
re.sub(r'\d+', lambda m: str(int(m.group()) * 2), 'a1b2')

1. 编译标志组合
p = re.compile(r'^\w+$', re.ASCII | re.IGNORECASE)

1. 逐步匹配
for m in re.finditer(r'\w+', text):
    print(m.start(), m.group())

注意事项

  • 循环里用 re.match 会每次编译——提取 Pattern 到模块级常量
  • match 只从开头匹配,任意位置用 search
  • 中文/Unicode 属性要加 re.UNICODE(3.x 默认已开)
  • 贪婪 .* 与懒惰 .*? 语义不同,跨行要 DOTALL

16. sqlite3 – 内嵌数据库

描述

标准库自带 SQL 数据库,适合本地数据与测试。连接默认非线程安全。

语法和示例

import sqlite3
con = sqlite3.connect('app.db')
con.execute('CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT)')
con.execute('INSERT INTO t (v) VALUES (?)', ('x',))
rows = con.execute('SELECT * FROM t').fetchall()
con.commit(); con.close()
with con:                                 # 上下文管理器自动 commit/rollback

1. 上下文管理器 + 行工厂
con = sqlite3.connect('app.db')
con.row_factory = sqlite3.Row
with con:
    con.execute('INSERT INTO t (v) VALUES (?)', ('x',))

row = con.execute('SELECT * FROM t LIMIT 1').fetchone()
row['v']                        # 按列名取值

1. 建索引与事务批处理
con.execute('CREATE INDEX IF NOT EXISTS idx_v ON t(v)')
con.executemany('INSERT INTO t (v) VALUES (?)', [('a',), ('b',)])

注意事项

  • 参数用 ? 占位,不要拼字符串(注入)
  • 默认 row_factory 是 tuple,要字典用 con.row_factory = sqlite3.Row
  • 多线程共享连接需 check_same_thread=False + 自己加锁
  • WAL 模式能提升并发读性能:PRAGMA journal_mode=WAL

17. urllib / http.client – 网络请求(标准库)

描述

标准库 HTTP 客户端。日常更推荐第三方 requests/httpx,标准库适合零依赖场景。

语法和示例

from urllib.request import urlopen, Request
with urlopen('https://example.com', timeout=10) as r:
    body = r.read().decode('utf-8')
req = Request(url, data=b'{}', headers={'Content-Type':'application/json'})
from urllib.parse import urlencode, quote, urlparse
urlencode({'q':'中文'}); quote('a b'); urlparse(u).query

注意事项

  • urlopen 不抛 HTTP 错误码异常,需自己检查 r.status
  • timeout 必须设,否则可能永久挂起
  • decode 要指定编码,否则按响应头猜可能出错
  • urlencode 用于查询串,路径段用 quote

这个系列的其他文档

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇