Python 标准库必备
一、文件与路径
pathlib(推荐)
pythonfrom pathlib import Path # 路径操作p = Path("/home/user/docs/report.txt")p.parent # Path("/home/user/docs")p.name # "report.txt"p.stem # "report"p.suffix # ".txt"p.exists()p.is_file()p.is_dir()p.mkdir(parents=True, exist_ok=True) # 路径拼接Path("data") / "input" / "file.csv" # 遍历for f in Path(".").glob("*.py"): print(f) for f in Path(".").rglob("*.py"): # 递归 print(f) # 读写Path("file.txt").write_text("hello", encoding="utf-8")content = Path("file.txt").read_text(encoding="utf-8")
os(传统方式)
pythonimport os os.path.join("a", "b", "c") # "a/b/c"(跨平台)os.path.exists("file.txt")os.path.isdir("mydir")os.path.basename("/path/to/file.txt") # "file.txt"os.path.dirname("/path/to/file.txt") # "/path/to"os.listdir(".") # 列出目录内容os.makedirs("a/b/c", exist_ok=True)os.remove("file.txt")os.rename("old.txt", "new.txt")os.environ # 环境变量字典os.getcwd() # 当前工作目录
二、sys — 系统相关
pythonimport sys sys.argv # 命令行参数列表,[0] 是脚本名sys.path # 模块搜索路径列表sys.exit(0) # 退出程序(0=正常)sys.stdin.read() # 读取标准输入sys.stdout.write("hello\n")sys.version # Python 版本字符串sys.platform # 平台标识(linux/darwin/win32)
三、JSON
pythonimport json d = {"name": "Alice", "age": 25, "languages": ["Python", "Java"]} # 序列化json_str = json.dumps(d) # 转 JSON 字符串json_str = json.dumps(d, indent=2) # 格式化json_str = json.dumps(d, ensure_ascii=False) # 保留中文 # 反序列化data = json.loads(json_str) # 从字符串解析 # 直接读写文件with open("data.json", "w") as f: json.dump(d, f, indent=2, ensure_ascii=False) with open("data.json", "r") as f: data = json.load(f)
四、CSV
pythonimport csv # 读with open("data.csv", "r") as f: reader = csv.reader(f) header = next(reader) # 跳过表头 for row in reader: print(row) # 以字典形式读with open("data.csv", "r") as f: reader = csv.DictReader(f) for row in reader: print(row["name"], row["age"]) # 写rows = [["Alice", 25], ["Bob", 30]]with open("out.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "age"]) # 写表头 writer.writerows(rows) # 以字典形式写with open("out.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["name", "age"]) writer.writeheader() writer.writerows([{"name": "Alice", "age": 25}])
五、日期与时间
pythonfrom datetime import datetime, date, time, timedeltaimport time as tm # 当前时间now = datetime.now()today = date.today() # 构造dt = datetime(2026, 7, 14, 15, 30, 0) # 格式化dt.strftime("%Y-%m-%d %H:%M:%S") # "2026-07-14 15:30:00"datetime.strptime("2026-07-14", "%Y-%m-%d") # 时间差delta = timedelta(days=7, hours=3)next_week = now + deltadiff = now - dt # timedelta 对象diff.days # 天数diff.total_seconds() # 总秒数 # 时间戳tm.time() # 当前 Unix 时间戳datetime.fromtimestamp(1700000000)now.timestamp() # datetime 转时间戳
常用格式化符号:
| 符号 | 含义 | 示例 |
|---|---|---|
| %Y | 四位年份 | 2026 |
| %m | 月份(01-12) | 07 |
| %d | 日期(01-31) | 14 |
| %H | 小时(00-23) | 15 |
| %M | 分钟(00-59) | 30 |
| %S | 秒(00-59) | 00 |
| %f | 微秒 | 000000 |
六、正则表达式(re)
pythonimport re text = "Contact: alice@example.com, bob@test.org" # 搜索re.search(r"(\w+)@(\w+\.\w+)", text) # 返回第一个 Match 对象re.findall(r"\w+@\w+\.\w+", text) # 返回所有匹配列表re.sub(r"\w+@\w+\.\w+", "[EMAIL]", text) # 替换 # 编译(复用性能更好)pattern = re.compile(r"\d{3}-\d{4}")pattern.match("123-4567 hello") # 从开头匹配pattern.search("tel: 123-4567") # 任意位置搜索pattern.findall("123-4567 987-6543") # 找所有 # 常用元字符# . 任意字符# \d 数字 \w 字母数字 \s 空白# * 0次+ + 1次+ ? 0或1次# {n} 恰好n次 {n,m} n到m次# ^ 开头 $ 结尾# [abc] 字符集 [^abc] 取反# () 分组 | 或
七、日志(logging)
pythonimport logging # 基本配置logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[ logging.FileHandler("app.log", encoding="utf-8"), logging.StreamHandler() # 也输出到控制台 ]) # 使用logger = logging.getLogger(__name__) # 推荐:每个模块一个 loggerlogger.debug("详细调试信息")logger.info("正常信息")logger.warning("警告信息")logger.error("错误信息")logger.critical("严重错误") # 异常日志try: 1 / 0except Exception: logger.exception("发生异常") # 自动包含 traceback
八、collections — 高级容器
pythonfrom collections import defaultdict, Counter, deque, namedtuple, OrderedDict # defaultdict — 带默认值的字典d = defaultdict(list) # 默认值为空列表d = defaultdict(int) # 默认值为 0d = defaultdict(lambda: "N/A")d["key"].append(1) # 即使 key 不存在也不会报错 # Counter — 计数器c = Counter("abracadabra")c.most_common(3) # [('a', 5), ('b', 2), ('r', 2)]c1 + c2 # 合并计数c1 - c2 # 差集 # deque — 双端队列(两端 O(1))q = deque([1, 2, 3])q.append(4) q.appendleft(0)q.pop() q.popleft()q.rotate(2) # 右移两个位置 # namedtuple — 命名元组Point = namedtuple("Point", ["x", "y"])p = Point(10, 20)p.x, p.y # 10, 20 # OrderedDict(3.7+ 普通 dict 也已保持插入顺序)od = OrderedDict()od["first"] = 1od["second"] = 2
九、itertools — 迭代器工具
pythonfrom itertools import chain, product, permutations, combinations, groupby, islice, cycle, count # chain — 串联多个迭代器list(chain([1, 2], [3, 4])) # [1, 2, 3, 4] # product — 笛卡尔积list(product("AB", [1, 2])) # [('A',1), ('A',2), ('B',1), ('B',2)] # permutations — 排列list(permutations([1, 2, 3], 2)) # 6 种排列 # combinations — 组合list(combinations([1, 2, 3], 2)) # (1,2), (1,3), (2,3) 共 3 种 # groupby — 分组(先排序!)data = [("a", 1), ("a", 2), ("b", 3)]for key, group in groupby(data, lambda x: x[0]): print(key, list(group)) # 无限迭代器(需配合 islice 截取)list(islice(cycle([1, 2, 3]), 7)) # [1, 2, 3, 1, 2, 3, 1]list(islice(count(10, 2), 5)) # [10, 12, 14, 16, 18]
十、functools
pythonfrom functools import lru_cache, partial, reduce # lru_cache — 缓存(记忆化)@lru_cache(maxsize=128)def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) # partial — 偏函数(固定部分参数)def power(base, exp): return base ** exp square = partial(power, exp=2)cube = partial(power, exp=3)square(5) # 25cube(5) # 125 # reduce — 累积运算reduce(lambda a, b: a * b, [1, 2, 3, 4]) # 24
十一、random — 随机数
pythonimport random random.random() # [0, 1) 随机浮点数random.randint(1, 10) # [1, 10] 随机整数random.uniform(1.5, 3.5) # [1.5, 3.5] 随机浮点数random.choice([1, 2, 3]) # 随机选一个random.choices([1, 2, 3], k=5) # 有放回抽 5 个random.sample([1, 2, 3, 4, 5], k=3) # 无放回抽 3 个random.shuffle(lst) # 原地打乱random.seed(42) # 固定随机种子(可复现)
十二、argparse — 命令行参数
pythonimport argparse parser = argparse.ArgumentParser(description="处理文件")parser.add_argument("input", help="输入文件路径")parser.add_argument("-o", "--output", default="output.txt", help="输出路径")parser.add_argument("-v", "--verbose", action="store_true", help="详细输出")parser.add_argument("-n", "--count", type=int, default=1, help="次数") args = parser.parse_args()print(args.input, args.output, args.verbose) # 运行: python script.py data.csv -o out.txt -v -n 5

