📚 15. 模块与包

本章概述

学习 Python 的模块导入、包的组织和常用标准库模块。 预计学习时间:50 分钟


15.1 什么是模块

一个 .py 文件就是一个模块(module)。

把代码分到不同的文件里,方便管理和复用。

示例

假设我们有一个 math_utils.py 文件:

# math_utils.py
def add(a, b):
    return a + b
 
def multiply(a, b):
    return a * b
 
PI = 3.14159

15.2 导入模块

import 模块名

import math_utils
 
print(math_utils.add(3, 5))      # 8
print(math_utils.multiply(3, 5)) # 15
print(math_utils.PI)              # 3.14159

from 模块 import 函数/变量

from math_utils import add, PI
 
print(add(3, 5))  # 8
print(PI)         # 3.14159

导入所有(不推荐)

from math_utils import *
 
print(add(3, 5))  # 8

尽量不要用 import *

  • 不知道导入了什么
  • 可能会和已有名字冲突
  • 代码可读性差

起别名 as

import math_utils as mu
 
print(mu.add(3, 5))  # 8
from math_utils import add as addition
 
print(addition(3, 5))  # 8

15.3 什么是包

包就是一个文件夹,里面放多个模块,还有一个 __init__.py 文件。

目录结构

my_package/
    __init__.py      # 包的标识文件
    math_utils.py    # 模块1
    string_utils.py  # 模块2

导入包中的模块

# 方式1
import my_package.math_utils
print(my_package.math_utils.add(3, 5))
 
# 方式2
from my_package import math_utils
print(math_utils.add(3, 5))
 
# 方式3
from my_package.math_utils import add
print(add(3, 5))

init.py 的作用

  • 标识这是一个包
  • 可以在里面写初始化代码
  • 可以定义 __all__ 来控制 import * 导入什么
# __init__.py
__all__ = ["math_utils", "string_utils"]

15.4 常用标准库模块

Python 自带了很多实用的模块,不用安装,直接用。

math 数学模块

import math
 
print(math.pi)           # 圆周率
print(math.e)            # 自然常数
print(math.sqrt(16))     # 开平方 4.0
print(math.floor(3.7))   # 向下取整 3
print(math.ceil(3.2))    # 向上取整 4
print(math.fabs(-5))     # 绝对值 5.0
print(math.factorial(5)) # 阶乘 120
print(math.log(100, 10)) # 对数 2.0
print(math.sin(math.pi/2)) # 正弦 1.0

random 随机模块

import random
 
# 随机整数(包含两端)
print(random.randint(1, 10))
 
# 随机浮点数 0~1
print(random.random())
 
# 随机浮点数(指定范围)
print(random.uniform(1, 10))
 
# 从序列中随机选一个
print(random.choice(["苹果", "香蕉", "橙子"]))
 
# 从序列中随机选多个(可重复)
print(random.choices([1, 2, 3, 4, 5], k=3))
 
# 从序列中随机选多个(不重复)
print(random.sample([1, 2, 3, 4, 5], 3))
 
# 打乱列表
lst = [1, 2, 3, 4, 5]
random.shuffle(lst)
print(lst)
 
# 设置随机种子(可复现)
random.seed(42)

datetime 日期时间模块

from datetime import datetime, date, timedelta
 
# 当前时间
now = datetime.now()
print(now)
 
# 指定时间
d = datetime(2024, 1, 1, 12, 0, 0)
print(d)
 
# 格式化输出
print(now.strftime("%Y-%m-%d %H:%M:%S"))
 
# 字符串转时间
s = "2024-01-01 12:00:00"
d = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
 
# 时间加减
tomorrow = now + timedelta(days=1)
yesterday = now - timedelta(days=1)
 
# 时间差
diff = tomorrow - yesterday
print(diff.days)  # 2

os 操作系统模块

import os
 
# 获取当前工作目录
print(os.getcwd())
 
# 切换目录
os.chdir("/path/to/dir")
 
# 列出目录内容
print(os.listdir("."))
 
# 创建目录
os.mkdir("new_dir")
 
# 创建多级目录
os.makedirs("a/b/c")
 
# 删除文件
os.remove("file.txt")
 
# 删除空目录
os.rmdir("dir")
 
# 判断是否存在
print(os.path.exists("file.txt"))
 
# 判断是否是文件
print(os.path.isfile("file.txt"))
 
# 判断是否是目录
print(os.path.isdir("dir"))
 
# 路径拼接
print(os.path.join("a", "b", "c.txt"))
 
# 获取文件名
print(os.path.basename("/a/b/c.txt"))  # c.txt
 
# 获取目录名
print(os.path.dirname("/a/b/c.txt"))   # /a/b
 
# 获取文件大小
print(os.path.getsize("file.txt"))

sys 系统模块

import sys
 
# Python 版本
print(sys.version)
 
# 命令行参数
print(sys.argv)
 
# 模块搜索路径
print(sys.path)
 
# 退出程序
sys.exit()
 
# 标准输入输出
sys.stdout.write("hello\n")

json JSON 模块

import json
 
# 字典转 JSON 字符串
data = {"name": "Tom", "age": 18}
json_str = json.dumps(data)
print(json_str)  # '{"name": "Tom", "age": 18}'
 
# JSON 字符串转字典
data = json.loads(json_str)
print(data["name"])  # Tom
 
# 写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
 
# 读取 JSON 文件
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

re 正则表达式模块

import re
 
# 匹配
result = re.match(r"\d+", "123abc")
print(result.group())  # 123
 
# 搜索
result = re.search(r"\d+", "abc123def")
print(result.group())  # 123
 
# 查找所有
results = re.findall(r"\d+", "a1b2c3")
print(results)  # ['1', '2', '3']
 
# 替换
result = re.sub(r"\d+", "X", "a1b2c3")
print(result)  # aXbXcX
 
# 分割
result = re.split(r"\d+", "a1b2c3")
print(result)  # ['a', 'b', 'c', '']

15.5 第三方库安装

pip 安装

pip install 包名
pip install requests
pip install pandas numpy

指定版本

pip install requests==2.28.0
pip install "requests>=2.0"

卸载

pip uninstall requests

查看已安装的包

pip list
pip freeze  # 格式更适合导出

导出/导入依赖

# 导出
pip freeze > requirements.txt
 
# 导入(批量安装)
pip install -r requirements.txt

15.6 模块搜索路径

Python 导入模块时,会按以下顺序查找:

  1. 当前目录
  2. 环境变量 PYTHONPATH 中的目录
  3. 标准库目录
  4. site-packages(第三方库安装目录)

可以用 sys.path 查看:

import sys
print(sys.path)

导入自己写的模块

确保模块文件在当前目录,或者把模块所在目录加到 sys.path 中。


15.7 if name == “main

Python 特色

判断当前文件是被直接运行,还是被导入。

示例

# math_utils.py
 
def add(a, b):
    return a + b
 
def multiply(a, b):
    return a * b
 
# 只有直接运行这个文件时才执行
if __name__ == "__main__":
    print("测试add函数:", add(3, 5))
    print("测试multiply函数:", multiply(3, 5))

为什么要用?

  • 直接运行文件时,可以执行测试代码
  • 被其他文件导入时,测试代码不会执行
  • 方便模块的测试和调试

🔗 相关章节


📝 我的笔记

在这里记录你的理解、疑问和练习代码

# 你的练习代码
 

✅ 本章检查清单

  • 理解什么是模块和包
  • 掌握各种 import 导入方式
  • 了解常用标准库模块(math、random、datetime、os、json等)
  • 会用 pip 安装第三方库
  • 理解模块搜索路径
  • 理解 if __name__ == "__main__" 的作用