Python 常用模块:别从头造轮子,这些内置的和第三方的直接拿来用
Python 最值钱的东西就是它的生态——标准库加上 PyPI 上几十万的第三方包,几乎覆盖了你可能遇到的所有需求。
写代码的时候,遇到问题第一反应不应该是”自己怎么实现”,而是”有没有现成的模块可以用”。
文件和路径:os、sys、pathlib
os:跟操作系统打交道
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import os
path = os.path.join("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 解释器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import sys
sys.argv
sys.exit(1)
if sys.version_info < (3, 8): print("需要 Python 3.8+") sys.exit(1)
sys.path sys.path.append("/my/custom/path")
sys.platform
|
pathlib:面向对象的路径操作(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| from pathlib import Path
p = Path("/home/user/data/file.txt") home = Path.home() current = Path.cwd()
p.name p.stem p.suffix p.parent
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from datetime import datetime, date, timedelta
now = datetime.now() today = date.today()
now.strftime("%Y-%m-%d %H:%M:%S") now.strftime("%Y年%m月%d日")
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
timestamp = now.timestamp() datetime.fromtimestamp(timestamp)
|
日期格式符记住 %Y-%m-%d %H:%M:%S 就够了,其他格式遇到再查。
JSON 处理:json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import json
data = {"name": "张三", "age": 25, "active": True}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
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(分割)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import re
text = "联系我:13812345678 或 email@test.com"
match = re.search(r"1[3-9]\d{9}", text) if match: print(match.group())
re.findall(r"1[3-9]\d{9}", text)
match = re.search(r"(\w+)@(\w+\.\w+)", text) match.group(1) match.group(2)
re.sub(r"1[3-9]\d{9}", "***", text)
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:不存在的键自动给默认值
1 2 3 4 5 6 7 8 9 10
| from collections import defaultdict
dd = defaultdict(list) dd["fruits"].append("apple") dd["fruits"]
dd_int = defaultdict(int) dd_int["count"] += 1
|
Counter:计数神器
1 2 3 4 5 6 7 8 9
| from collections import Counter
words = ["apple", "banana", "apple", "orange", "apple", "banana"] counter = Counter(words)
counter.most_common(2) counter["apple"] counter["grape"]
|
deque:两端操作 O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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)
|
product:多层循环替代品
1 2 3 4 5 6 7 8 9
| from itertools import product
colors = ["红", "蓝"] sizes = ["S", "M", "L"]
for c, s in product(colors, sizes): print(f"{c}{s}")
|
permutations 和 combinations:排列组合
1 2 3 4
| from itertools import permutations, combinations
list(permutations([1, 2, 3], 2)) list(combinations([1, 2, 3, 4], 2))
|
chain:串联多个列表
1 2 3
| from itertools import chain
list(chain([1, 2], [3, 4], [5, 6]))
|
lru_cache:函数结果缓存
1 2 3 4 5 6 7 8 9 10
| from functools import lru_cache
@lru_cache(maxsize=128) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2)
fib(40) fib.cache_info()
|
partial:固定部分参数,生成新函数
1 2 3 4 5 6 7 8 9 10
| from functools import partial
def power(base, exponent): return base ** exponent
square = partial(power, exponent=2) cube = partial(power, exponent=3)
square(5) cube(5)
|
日志:logging
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 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(第三方)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import requests
resp = requests.get("https://api.github.com") resp.status_code resp.json()
resp = requests.get("https://api.github.com/search/repositories", params={"q": "python", "page": 1})
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() except requests.exceptions.Timeout: print("超时") except requests.exceptions.ConnectionError: print("连接失败")
|
session 保持登录状态:
1 2 3 4
| session = requests.Session() session.post("https://example.com/login", data={"user": "alice", "pass": "123"})
profile = session.get("https://example.com/profile")
|
数据分析三件套:pandas、numpy、matplotlib
pandas:处理表格数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import pandas as pd
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:数值计算
1 2 3 4 5 6 7 8 9 10 11 12 13
| import numpy as np
arr = np.array([1, 2, 3, 4, 5]) arr.mean() arr.sum() arr.max() arr[arr > 2]
np.zeros((3, 4)) np.ones((2, 3)) np.arange(0, 10, 2) np.random.rand(3, 3)
|
matplotlib:画图
1 2 3 4 5 6 7 8 9 10 11
| 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()
|