Skip to content

第十章:常用标准库

os — 操作系统交互

bash
import os

# 当前工作目录
print(f"当前目录:{os.getcwd()}")

# 列出目录内容
files = os.listdir(".")
print(f"当前目录下有 {len(files)} 个文件/文件夹")

# 创建目录
os.makedirs("test_dir/sub_dir", exist_ok=True)
print("目录创建完成")

# 路径操作(推荐使用 os.path 或 pathlib)
file_path = os.path.join("test_dir", "sub_dir", "data.txt")
print(f"拼接路径:{file_path}")
print(f"文件名:{os.path.basename(file_path)}")
print(f"目录名:{os.path.dirname(file_path)}")
print(f"文件存在?{os.path.exists(file_path)}")
bash
当前目录:/home/user/project
当前目录下有 5 个文件/文件夹
目录创建完成
拼接路径:test_dir/sub_dir/data.txt
文件名:data.txt
目录名:test_dir/sub_dir
文件存在?False

datetime — 日期时间

bash
from datetime import datetime, timedelta

now = datetime.now()
print(f"当前时间:{now}")
print(f"格式化:{now.strftime('%Y年%m月%d日 %H:%M:%S')}")
print(f"星期{now.isoweekday()}")

# 时间计算
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')}")

# 字符串 → 日期
birthday = datetime.strptime("1999-06-15", "%Y-%m-%d")
age_days = (now - birthday).days
print(f"你已经活了 {age_days} 天(约 {age_days // 365} 岁)")
bash
当前时间:2025-06-20 14:30:25.123456
格式化:2025年06月20日 14:30:25
星期5
明天:2025-06-21
上周:2025-06-13
你已经活了 9496 天(约 25 岁)

re — 正则表达式

bash
import re

text = "我的手机号是 13812345678,邮箱是 test@example.com,备用:hello_world@gmail.com"

# 提取手机号
phone = re.search(r'1[3-9]\d{9}', text)
print(f"手机号:{phone.group()}")

# 提取所有邮箱
emails = re.findall(r'[\w.-]+@[\w.-]+\.\w+', text)
print(f"邮箱:{emails}")

# 替换敏感信息
masked = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1\2', text)
print(f"脱敏后:{masked}")

# 验证格式
is_valid = bool(re.match(r'^\d{6}$', "100086"))
print(f"邮编验证:{is_valid}")
bash
手机号:13812345678
邮箱:['test@example.com', 'hello_world@gmail.com']
脱敏后:我的手机号是 1385678,邮箱是 test@example.com,备用:hello_world@gmail.com
邮编验证:True

collections — 增强集合

bash
from collections import Counter, defaultdict, namedtuple

# Counter:计数器
words = "the quick brown fox jumps over the lazy dog the fox".split()
count = Counter(words)
print("词频统计:")
for word, freq in count.most_common(3):
    print(f"  '{word}' 出现 {freq} 次")

# defaultdict:带默认值的字典
grades = defaultdict(list)
scores = [("数学", 85), ("语文", 92), ("数学", 78), ("英语", 90), ("语文", 88)]
for subject, score in scores:
    grades[subject].append(score)
print(f"\n各科成绩:{dict(grades)}")

# namedtuple:有名字的元组
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(f"\n坐标:({p.x}, {p.y})")
bash
词频统计:
  'the' 出现 3
  'fox' 出现 2
  'quick' 出现 1

各科成绩:{'数学': [85, 78], '语文': [92, 88], '英语': [90]}

坐标:(3, 4)

itertools — 迭代利器

bash
import itertools

# 无限计数器
counter = itertools.count(start=1, step=2)
first_five = [next(counter) for _ in range(5)]
print(f"奇数序列:{first_five}")

# 排列组合
items = ["A", "B", "C"]
perms = list(itertools.permutations(items, 2))
print(f"排列 P(3,2):{perms}")

combos = list(itertools.combinations(items, 2))
print(f"组合 C(3,2):{combos}")

# 分组
data = sorted([("动物", "猫"), ("水果", "苹果"), ("动物", "狗"), ("水果", "香蕉")],
              key=lambda x: x[0])
for key, group in itertools.groupby(data, key=lambda x: x[0]):
    items_in_group = [item[1] for item in group]
    print(f"  {key}:{items_in_group}")
bash
奇数序列:[1, 3, 5, 7, 9]
排列 P(3,2):[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
组合 C(3,2):[('A', 'B'), ('A', 'C'), ('B', 'C')]
  动物:['猫', '狗']
  水果:['苹果', '香蕉']

sys — 系统相关

bash
import sys

print(f"Python 版本:{sys.version}")
print(f"平台:{sys.platform}")
print(f"默认编码:{sys.getdefaultencoding()}")
print(f"递归深度限制:{sys.getrecursionlimit()}")
print(f"命令行参数:{sys.argv}")

# 查看已安装模块数量
print(f"已加载模块数:{len(sys.modules)}")
bash
Python 版本:3.12.4 (main, Jun  8 2025, 11:20:00) [GCC 11.4.0]
平台:linux
默认编码:utf-8
递归深度限制:1000
命令行参数:['script.py']
已加载模块数:67