🚀 一、标准库整体认知

Python 标准库常被称为:

👉 Python Standard Library

特点:

  • 自带(无需安装)
  • 覆盖面极广(文件、网络、并发、数据处理…)
  • 稳定可靠(生产级)

🧱 二、最核心模块(必须掌握)

1️⃣ 文件 & 系统操作(天天用)

📦 os / pathlib

Image

Image

Image

Image

Image

Image

Image

import os
from pathlib import Path

# 当前目录
print(os.getcwd())

# 列出文件
print(os.listdir("."))

# pathlib(推荐)
p = Path(".")
for file in p.iterdir():
    print(file)

👉 建议:
以后优先用 pathlib(更现代、跨平台)


2️⃣ 数据结构增强

📦 collections

from collections import Counter, defaultdict

# 计数
print(Counter("aabbbc"))

# 默认字典
d = defaultdict(int)
d["a"] += 1
print(d)

👉 用处:

  • 统计(日志分析)
  • 分组数据
  • 队列(deque)

3️⃣ 时间处理

📦 datetime

Image

Image

Image

Image

from datetime import datetime, timedelta

now = datetime.now()
print(now)

# 时间格式化
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# 时间计算
print(now + timedelta(days=1))

👉 场景:

  • 日志
  • 定时任务
  • 数据统计

4️⃣ JSON处理(接口核心)

📦 json

import json

data = {"name": "Alice", "age": 20}

# 转字符串
s = json.dumps(data)

# 转对象
obj = json.loads(s)

print(s, obj)

👉 你做接口/自动化,这个是必用


5️⃣ 随机 & 数学

📦 random / math

import random
import math

print(random.randint(1, 10))
print(math.sqrt(16))

⚙️ 三、进阶核心模块(工程必会)

6️⃣ 函数增强

📦 functools

from functools import lru_cache

@lru_cache()
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(10))

👉 用处:

  • 缓存(性能优化)
  • 装饰器增强

7️⃣ 迭代工具

📦 itertools

import itertools

for item in itertools.permutations([1,2,3], 2):
    print(item)

👉 用处:

  • 排列组合
  • 数据遍历优化

8️⃣ 多线程 / 多进程

📦 threading / multiprocessing

import threading

def task():
    print("线程执行")

t = threading.Thread(target=task)
t.start()
t.join()

👉 用途:

  • IO并发(接口调用)
  • CPU计算(用 multiprocessing)

9️⃣ 异步核心

📦 asyncio(重点)

import asyncio

async def main():
    await asyncio.sleep(1)
    print("完成")

asyncio.run(main())

👉 你做自动化/接口,这个非常关键


🌐 四、网络相关(你很适合)

10️⃣ HTTP

📦 urllib

from urllib import request

resp = request.urlopen("https://example.com")
print(resp.read())

👉 实际建议:

  • 标准库了解即可
  • 实战用 requests / aiohttp

11️⃣ socket(底层通信)

import socket

s = socket.socket()
print("socket 创建成功")

👉 你做 PLC / TCP 通信 → 这个非常重要


🧰 五、调试 & 系统

12️⃣ sys

import sys

print(sys.argv)

13️⃣ logging(强烈推荐)

import logging

logging.basicConfig(level=logging.INFO)
logging.info("日志输出")

👉 企业项目必须用,不要再用 print


📦 六、压缩 / 文件处理

14️⃣ zipfile

import zipfile

with zipfile.ZipFile("test.zip", "w") as z:
    z.writestr("a.txt", "hello")

🧠 七、怎么学才有效(重点)

别背模块,要按“场景”学:

🔥 场景驱动学习

场景 必学库
文件处理 os / pathlib
接口开发 json / datetime
自动化 asyncio / threading
数据分析 collections / itertools
系统开发 logging / sys
工业通信 socket

🎯 建议

  • Playwright 自动化 ✅
  • 接口调用 ✅
  • 工业系统 / PLC ✅

👉 推荐重点:

  1. asyncio(接口并发)
  2. socket(设备通信)
  3. logging(工程规范)
  4. collections(数据处理)

🚀 再进一层

  • 🔹 写一个“接口压测工具”(用 asyncio)
  • 🔹 写一个“日志系统”(logging + 文件)
  • 🔹 写一个“TCP客户端”(socket + 重连机制)

直接把标准库用到“工程级”。

更多推荐