模块与包
学习目标
- 理解模块和包的概念
- 掌握
import的各种用法 - 了解 Python 常用标准库
- 学会使用
pip安装第三方库 - 能创建和使用自己的模块
什么是模块?
到目前为止,你的所有代码都写在一个文件里。但当项目变大后,一个文件可能有几千行代码——这太难管理了。
模块(module)就是一个 .py 文件。 你可以把相关的函数、类、变量放在一个模块里,然后在其他文件中导入使用。
想象你在搬家:
- 把衣服放一个箱子(
clothes.py) - 把书籍放一个箱子(
books.py) - 把厨具放一个箱子(
kitchen.py)
每个箱子就是一个模块,需要什么就打开对应的箱子。
import 的基本用法
导入整个模块
import math
# 使用时需要加模块名前缀
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4(向上取整)
print(math.floor(3.8)) # 3(向下取整)
从模块中导入特定内容
from math import pi, sqrt
# 直接使用,不需要模块名前缀
print(pi) # 3.141592653589793
print(sqrt(16)) # 4.0
导入并起别名
import numpy as np # 给 numpy 起个简短的别名
import pandas as pd # pandas 的标准别名
# AI 领域的约定俗成的别名
import matplotlib.pyplot as plt
import tensorflow as tf
import torch
导入模块中的所有内容
from math import *
# 可以直接用所有内容
print(pi)
print(sqrt(16))
print(sin(0))
不推荐 from xxx import *
虽然看起来很方便,但它会把模块里所有名字都导入当前文件,可能导致命名冲突(两个模块里有同名函数)。而且别人读你的代码时,不知道某个函数是从哪个模块来的。
推荐的做法:
import math然后用math.sqrt()(最明确)from math import sqrt, pi(只导入需要的)
Python 常用标准库
Python 自带了很多实用的模块,安装 Python 后就能直接用,不需要额外安装。
math —— 数学运算
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(144)) # 12.0
print(math.pow(2, 10)) # 1024.0
print(math.log(100, 10)) # 2.0(以 10 为底的对数)
print(math.sin(math.pi / 2)) # 1.0
print(math.factorial(5)) # 120(5! = 5×4×3×2×1)
random —— 随机数
import random
# 随机整数
print(random.randint(1, 100)) # 1 到 100 之间的随机整数
# 随机浮点数
print(random.random()) # 0 到 1 之间的随机浮点数
print(random.uniform(1.0, 10.0)) # 1.0 到 10.0 之间
# 从列表中随机选择
colors = ["红", "绿", "蓝", "黄"]
print(random.choice(colors)) # 随机选一个
print(random.sample(colors, 2)) # 随机选 2 个(不重复)
# 打乱列表
cards = list(range(1, 14))
random.shuffle(cards)
print(cards) # 打乱后的列表
# 设置随机种子(让结果可复现——AI 训练中常用)
random.seed(42)
print(random.randint(1, 100)) # 每次运行结果都一样
os —— 操作系统交互
import os
# 获取当前工作目录
print(os.getcwd())
# 列出目录中的文件
print(os.listdir("."))
# 检查文件/目录是否存在
print(os.path.exists("hello.py"))
# 拼接路径(跨平台兼容)
path = os.path.join("data", "train", "images")
print(path) # data/train/images(macOS/Linux)或 data\train\images(Windows)
# 获取文件名和扩展名
filename = "model_v2.pth"
name, ext = os.path.splitext(filename)
print(f"文件名: {name}, 扩展名: {ext}") # 文件名: model_v2, 扩展名: .pth
# 创建目录
os.makedirs("output/results", exist_ok=True) # exist_ok=True 表示已存在时不报错
datetime —— 日期时间
from datetime import datetime, timedelta
# 获取当前时间
now = datetime.now()
print(now) # 2026-02-09 14:30:45.123456
print(now.strftime("%Y-%m-%d")) # 2026-02-09
print(now.strftime("%Y年%m月%d日")) # 2026年02月09日
# 时间计算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
print(f"明天: {tomorrow.strftime('%Y-%m-%d')}")
print(f"上周: {last_week.strftime('%Y-%m-%d')}")
# 解析时间字符串
date_str = "2026-01-15"
date = datetime.strptime(date_str, "%Y-%m-%d")
print(date)
json —— JSON 数据处理
import json
# Python 对象 → JSON 字符串
data = {
"name": "小明",
"age": 20,
"scores": [85, 92, 78],
"is_student": True
}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 字符串 → Python 对象
parsed = json.loads(json_str)
print(parsed["name"]) # 小明
# 读写 JSON 文件
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:
loaded = json.load(f)
print(loaded)
标准库速查表
| 模块 | 用途 | 常用功能 |
|---|---|---|
math | 数学运算 | sqrt, pi, sin, log |
random | 随机数 | randint, choice, shuffle |
os | 操作系统 | getcwd, listdir, path.join |
datetime | 日期时间 | now, strftime, timedelta |
json | JSON 处理 | dumps, loads, dump, load |
re | 正则表达式 | search, findall, sub |
collections | 高级容器 | Counter, defaultdict |
pathlib | 路径操作 | Path, glob, mkdir |
sys | 系统参数 | argv, path, exit |
time | 时间相关 | sleep, time |