Python 常用内置模块大全 📚
Python 拥有丰富的内置模块库,让我们来看看最常用和最重要的模块!
🏆 核心常用模块(必学)
1. 文件与操作系统相关
os - 操作系统接口 🖥️
import os
# 文件和目录操作
os.listdir('.') # 列出目录内容
os.mkdir('new_folder') # 创建目录
os.rename('old', 'new') # 重命名
os.remove('file.txt') # 删除文件
# 路径操作
current_dir = os.getcwd() # 获取当前目录
os.path.join('folder', 'file.txt') # 拼接路径
os.path.exists('file.txt') # 检查文件是否存在
sys - 系统相关参数 🛠️
import sys
print(sys.version) # Python 版本
print(sys.platform) # 操作系统平台
sys.exit(0) # 退出程序
# 命令行参数
if len(sys.argv) > 1:
filename = sys.argv[1] # 获取命令行参数
pathlib - 现代路径操作 🗺️
from pathlib import Path
# 更现代的路径操作方式
current = Path('.')
file_path = current / 'data' / 'file.txt' # 路径拼接
if file_path.exists():
content = file_path.read_text()
2. 数据处理与编码
json - JSON 数据处理 📄
import json
# Python 对象 → JSON 字符串
data = {'name': '小明', 'age': 12, 'scores': [95, 88, 92]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
# JSON 字符串 → Python 对象
parsed_data = json.loads(json_str)
# 文件操作
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
csv - CSV 文件处理 📊
import csv
# 读取 CSV
with open('students.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"姓名: {row['name']}, 分数: {row['score']}")
# 写入 CSV
with open('output.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['姓名', '年龄', '分数'])
writer.writerow(['小明', '12', '95'])
3. 日期与时间
datetime - 日期时间处理 📅
from datetime import datetime, date, timedelta
# 当前时间
now = datetime.now()
print(f"现在时间: {now}")
print(f"格式化: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# 日期运算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
# 创建特定日期
birthday = datetime(2024, 12, 25, 10, 30, 0)
time - 时间相关功能 ⏰
import time
print(time.time()) # 时间戳
time.sleep(2) # 暂停 2 秒
# 性能测试
start = time.time()
# 执行一些操作...
end = time.time()
print(f"耗时: {end - start:.2f} 秒")
4. 数学与随机数
math - 数学函数 🔢
import math
print(math.pi) # 圆周率
print(math.sqrt(16)) # 平方根
print(math.pow(2, 3)) # 幂运算
print(math.floor(3.7)) # 向下取整
print(math.ceil(3.2)) # 向上取整
print(math.sin(math.pi/2)) # 三角函数
random - 随机数生成 🎲
import random
print(random.random()) # 0-1 随机小数
print(random.randint(1, 100)) # 1-100 随机整数
print(random.choice(['苹果', '香蕉', '橙子'])) # 随机选择
# 随机打乱列表
cards = ['A', '2', '3', '4', '5']
random.shuffle(cards)
print(cards)
# 随机抽样
sample = random.sample(range(100), 5) # 从0-99中抽取5个不重复的数
5. 数据集合与算法
collections - 特殊容器类型 📦
from collections import Counter, defaultdict, deque
# 计数器
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(words)
print(word_count.most_common(2)) # 出现次数最多的2个
# 默认字典 - 避免 KeyError
student_scores = defaultdict(list)
student_scores['小明'].append(95) # 自动创建空列表
# 双端队列
queue = deque(['A', 'B', 'C'])
queue.append('D') # 右边添加
queue.appendleft('Z') # 左边添加
queue.pop() # 右边移除
itertools - 迭代器工具 ♻️
import itertools
# 无限迭代器
counter = itertools.count(1, 2) # 从1开始,步长为2
print(next(counter)) # 1
print(next(counter)) # 3
# 排列组合
letters = ['A', 'B', 'C']
combinations = list(itertools.combinations(letters, 2)) # 组合
permutations = list(itertools.permutations(letters, 2)) # 排列
📚 其他重要内置模块
6. 网络与互联网
urllib - URL 处理 🌐
from urllib.request import urlopen
import urllib.parse
# 读取网页内容
with urlopen('https://httpbin.org/json') as response:
content = response.read().decode('utf-8')
print(content)
# URL 编码解码
encoded = urllib.parse.quote('编程教程')
decoded = urllib.parse.unquote(encoded)
7. 数据类型扩展
enum - 枚举类型 🎯
from enum import Enum, auto
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Direction(Enum):
UP = auto() # 自动赋值
DOWN = auto()
LEFT = auto()
RIGHT = auto()
print(Color.RED) # Color.RED
print(Color.RED.value) # 1
8. 功能增强模块
functools - 高阶函数 🔧
from functools import lru_cache, partial
# 缓存装饰器 - 优化递归函数
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 偏函数 - 固定部分参数
def multiply(x, y):
return x * y
double = partial(multiply, 2) # 固定第一个参数为2
print(double(5)) # 10
🎯 教学重点模块总结
初学者必学(中小学教学)📝
| 模块 | 主要用途 | 教学示例 |
|---|---|---|
math |
数学计算 | 几何计算、函数图像 |
random |
随机数 | 抽奖程序、游戏 |
datetime |
日期时间 | 倒计时、生日计算 |
json |
数据存储 | 学生成绩管理 |
os |
文件操作 | 文件管理器 |
tkinter |
图形界面 | 计算器、小游戏 |
进阶学习模块 🚀
| 模块 | 主要用途 | 应用场景 |
|---|---|---|
collections |
高级数据结构 | 数据分析、统计 |
itertools |
迭代工具 | 算法优化、组合问题 |
sqlite3 |
数据库 | 数据持久化存储 |
threading |
多线程 | 并发程序 |
re |
正则表达式 | 文本处理、数据提取 |
💡 实用示例:学生成绩管理系统
import json
import os
from datetime import datetime
from collections import defaultdict
class StudentManager:
def __init__(self, filename='students.json'):
self.filename = filename
self.students = self.load_data()
def load_data(self):
"""从文件加载数据"""
if os.path.exists(self.filename):
with open(self.filename, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save_data(self):
"""保存数据到文件"""
with open(self.filename, 'w', encoding='utf-8') as f:
json.dump(self.students, f, ensure_ascii=False, indent=2)
def add_student(self, name, scores):
"""添加学生成绩"""
self.students[name] = {
'scores': scores,
'average': sum(scores) / len(scores),
'update_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
self.save_data()
print(f"✅ 成功添加学生 {name}")
def show_all(self):
"""显示所有学生"""
for name, info in self.students.items():
print(f"👤 {name}: 成绩{info['scores']} 平均分{info['average']:.1f}")
# 使用示例
if __name__ == "__main__":
manager = StudentManager()
manager.add_student('小明', [95, 88, 92])
manager.add_student('小红', [90, 85, 95])
manager.show_all()
🎓 学习建议
学习路径 📈
- 初级阶段:
math,random,datetime - 中级阶段:
os,json,csv - 高级阶段:
collections,itertools,functools
教学技巧 💡
- 项目驱动:每个模块配合一个小项目学习
- 可视化展示:用图形展示模块功能
- 实际应用:结合学生生活场景举例
- 循序渐进:从简单功能开始,逐步深入
✨ 记住:Python 的内置模块就像工具包里的各种工具,学会正确使用它们能让编程事半功倍!选择适合学生水平的模块开始教学,让学习过程既有挑战性又有成就感!🎉
请登录后发表评论
登录后你可以点赞、回复其他评论