Python3 常用模块:提升开发效率的必备工具
Python 常用模块:别从头造轮子,这些内置的和第三方的直接拿来用
Python 最值钱的东西就是它的生态——标准库加上 PyPI 上几十万的第三方包,几乎覆盖了你可能遇到的所有需求。
写代码的时候,遇到问题第一反应不应该是”自己怎么实现”,而是”有没有现成的模块可以用”。
文件和路径:os、sys、pathlib
os:跟操作系统打交道
import os
# 路径拼接(跨平台)
path = os.path.join("data", "logs", "app.log") # data/logs/app.log
# 获取当前目录
os.getcwd()
# 创建目录(存在也不报错)
os.makedirs("data/logs", exist_ok=True)
# 判断文件/目录是否存在
os.path.exists("data.txt")
os.path.isfile("data.txt")
os.path.isdir("data")
# 列出目录内容
os.listdir(".")
# 删除文件
os.remove("temp.txt")
# 环境变量
os.environ.get("PATH")
sys:控制 Python 解释器
import sys
# 命令行参数
# python script.py --name Alice
sys.argv # ['script.py', '--name', 'Alice']
# 程序退出
sys.exit(1) # 非0表示异常
# Python 版本检查
if sys.version_info < (3, 8):
print("需要 Python 3.8+")
sys.exit(1)
# 模块搜索路径
sys.path
sys.path.append("/my/custom/path")
# 平台信息
sys.platform # 'linux', 'win32', 'darwin'
pathlib:面向对象的路径操作(推荐)
from pathlib import Path
# 创建路径
p = Path("/home/user/data/file.txt")
home = Path.home()
current = Path.cwd()
# 路径属性
p.name # 'file.txt'
p.stem # 'file'
p.suffix # '.txt'
p.parent # '/home/user/data'
# 拼接(用 / 运算符)
path = Path("data") / "logs" / "app.log"
# 读写文件(一行搞定)
Path("data.txt").write_text("Hello", encoding="utf-8")
content = Path("data.txt").read_text(encoding="utf-8")
# 遍历文件
for file in Path(".").glob("*.py"):
print(file)
# 递归遍历
for file in Path(".").rglob("*.txt"):
print(file)
# 创建目录
Path("data/logs").mkdir(parents=True, exist_ok=True)
# 判断存在
if Path("data.txt").exists():
Path("data.txt").unlink() # 删除
os 还是 pathlib? pathlib 是新代码的推荐选择,更直观、跨平台更好。老代码里 os.path 也很常见,两种都认识就行。
日期时间:datetime
from datetime import datetime, date, timedelta
# 获取当前时间
now = datetime.now()
today = date.today()
# 格式化输出
now.strftime("%Y-%m-%d %H:%M:%S") # '2026-07-02 10:30:00'
now.strftime("%Y年%m月%d日") # '2026年07月02日'
# 字符串转 datetime
dt = datetime.strptime("2026-07-02 10:30:00", "%Y-%m-%d %H:%M:%S")
# 时间计算
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
yesterday = now - timedelta(days=1)
# 时间差
delta = datetime(2026, 12, 31) - datetime(2026, 1, 1)
delta.days # 364
# 时间戳
timestamp = now.timestamp()
datetime.fromtimestamp(timestamp)
日期格式符记住 %Y-%m-%d %H:%M:%S 就够了,其他格式遇到再查。
JSON 处理:json
import json
data = {"name": "张三", "age": 25, "active": True}
# 字典 → JSON 字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)
# {
# "name": "张三",
# "age": 25,
# "active": true
# }
# JSON 字符串 → 字典
parsed = json.loads('{"name": "张三", "age": 25}')
# 读写文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
记住两个参数: ensure_ascii=False 保留中文,indent=2 让输出可读。
正则表达式:re
常用函数就四个:search(找一个)、findall(找所有)、sub(替换)、split(分割)。
import re
text = "联系我:13812345678 或 email@test.com"
# 找第一个
match = re.search(r"1[3-9]\d{9}", text)
if match:
print(match.group()) # '13812345678'
# 找所有
re.findall(r"1[3-9]\d{9}", text) # ['13812345678']
# 找所有 + 捕获组
match = re.search(r"(\w+)@(\w+\.\w+)", text)
match.group(1) # 'email'
match.group(2) # 'test.com'
# 替换
re.sub(r"1[3-9]\d{9}", "***", text) # '联系我:*** 或 email@test.com'
# 预编译(多次使用时提升性能)
pattern = re.compile(r"1[3-9]\d{9}")
pattern.findall(text)
常用正则速查:
| 需求 | 正则 |
|---|---|
| 手机号 | 1[3-9]\d{9} |
| 邮箱 | \w+@\w+\.\w+ |
| URL | https?://[^\s]+ |
| 数字 | \d+ |
| 中文 | [\u4e00-\u9fa5]+ |
高级数据结构:collections
defaultdict:不存在的键自动给默认值
from collections import defaultdict
# 默认值是列表
dd = defaultdict(list)
dd["fruits"].append("apple") # 不会报 KeyError
dd["fruits"] # ['apple']
# 默认值是数字 0
dd_int = defaultdict(int)
dd_int["count"] += 1 # 1
Counter:计数神器
from collections import Counter
words = ["apple", "banana", "apple", "orange", "apple", "banana"]
counter = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})
counter.most_common(2) # [('apple', 3), ('banana', 2)]
counter["apple"] # 3
counter["grape"] # 0(不存在的返回0,不报错)
deque:两端操作 O(1)
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # 右边加
dq.appendleft(0) # 左边加
dq.pop() # 右边删
dq.popleft() # 左边删
# 固定长度,满了自动挤掉旧的
dq = deque(maxlen=3)
for i in range(5):
dq.append(i)
# deque([2, 3, 4], maxlen=3)
迭代器工具:itertools
product:多层循环替代品
from itertools import product
colors = ["红", "蓝"]
sizes = ["S", "M", "L"]
# 替代嵌套 for
for c, s in product(colors, sizes):
print(f"{c}{s}")
# 红S, 红M, 红L, 蓝S, 蓝M, 蓝L
permutations 和 combinations:排列组合
from itertools import permutations, combinations
list(permutations([1, 2, 3], 2)) # 排列,有序
list(combinations([1, 2, 3, 4], 2)) # 组合,无序不重复
chain:串联多个列表
from itertools import chain
list(chain([1, 2], [3, 4], [5, 6])) # [1, 2, 3, 4, 5, 6]
缓存和偏函数:functools
lru_cache:函数结果缓存
from functools import lru_cache
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
fib(40) # 第一次慢,之后直接从缓存取
fib.cache_info() # 查看缓存命中情况
partial:固定部分参数,生成新函数
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
square(5) # 25
cube(5) # 125
日志:logging
import logging
# 基础配置
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
logger.debug("调试")
logger.info("信息")
logger.warning("警告")
logger.error("错误")
logger.critical("严重")
# 记录异常堆栈
try:
1 / 0
except Exception:
logger.exception("发生异常")
HTTP 请求:requests(第三方)
import requests
# GET 请求
resp = requests.get("https://api.github.com")
resp.status_code # 200
resp.json() # 解析 JSON
# GET 带参数
resp = requests.get("https://api.github.com/search/repositories",
params={"q": "python", "page": 1})
# POST JSON
resp = requests.post("https://httpbin.org/post",
json={"username": "alice", "password": "secret"})
# 错误处理
try:
resp = requests.get("https://api.example.com", timeout=5)
resp.raise_for_status() # 4xx/5xx 抛异常
except requests.exceptions.Timeout:
print("超时")
except requests.exceptions.ConnectionError:
print("连接失败")
session 保持登录状态:
session = requests.Session()
session.post("https://example.com/login", data={"user": "alice", "pass": "123"})
# 后续请求自动带 cookies
profile = session.get("https://example.com/profile")
数据分析三件套:pandas、numpy、matplotlib
pandas:处理表格数据
import pandas as pd
# 读 CSV / Excel
df = pd.read_csv("data.csv")
df = pd.read_excel("data.xlsx")
# 看一眼数据
df.head()
df.info()
df.describe()
# 筛选
df[df["age"] > 25]
df[(df["age"] > 25) & (df["score"] > 85)]
# 分组聚合
df.groupby("city")["score"].mean()
# 写回文件
df.to_csv("output.csv", index=False)
numpy:数值计算
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr.mean() # 3.0
arr.sum() # 15
arr.max() # 5
arr[arr > 2] # 条件筛选 [3, 4, 5]
# 创建数组
np.zeros((3, 4)) # 3x4 全0
np.ones((2, 3)) # 2x3 全1
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.random.rand(3, 3) # 3x3 随机数
matplotlib:画图
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("正弦曲线")
plt.show()