标准库 #
Python标准库提供了丰富的功能模块。
一、os模块 - 操作系统接口 #
python
import os
# 环境变量
print(os.environ)
print(os.getenv('HOME'))
# 文件和目录
os.getcwd() # 当前目录
os.chdir('/path') # 切换目录
os.listdir('.') # 列出目录内容
os.mkdir('new_dir') # 创建目录
os.makedirs('a/b/c') # 递归创建目录
os.rmdir('dir') # 删除空目录
os.remove('file.txt') # 删除文件
os.rename('old', 'new') # 重命名
# 路径操作
os.path.exists('file.txt') # 是否存在
os.path.isfile('file.txt') # 是否是文件
os.path.isdir('dir') # 是否是目录
os.path.join('a', 'b', 'c') # 拼接路径
os.path.split('/a/b/c.txt') # ('/a/b', 'c.txt')
os.path.splitext('file.txt') # ('file', '.txt')
二、sys模块 - 系统相关 #
python
import sys
print(sys.version) # Python版本
print(sys.path) # 模块搜索路径
print(sys.argv) # 命令行参数
sys.exit(0) # 退出程序
三、math模块 - 数学函数 #
python
import math
print(math.pi) # 3.14159...
print(math.e) # 2.71828...
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3
print(math.log(10)) # 自然对数
print(math.log10(100)) # 2.0
print(math.sin(math.pi/2)) # 1.0
四、random模块 - 随机数 #
python
import random
print(random.random()) # 0.0-1.0随机浮点数
print(random.randint(1, 10)) # 1-10随机整数
print(random.choice([1, 2, 3])) # 随机选择
print(random.sample([1,2,3], 2)) # 随机抽样
random.shuffle([1, 2, 3]) # 打乱顺序
五、datetime模块 - 日期时间 #
python
from datetime import datetime, date, time, timedelta
# 当前时间
now = datetime.now()
today = date.today()
# 创建日期时间
d = date(2024, 3, 16)
t = time(10, 30, 0)
dt = datetime(2024, 3, 16, 10, 30, 0)
# 格式化
print(now.strftime('%Y-%m-%d %H:%M:%S'))
# 解析
dt = datetime.strptime('2024-03-16', '%Y-%m-%d')
# 时间差
delta = timedelta(days=7)
future = now + delta
六、json模块 - JSON处理 #
python
import json
# 编码
data = {"name": "Tom", "age": 25}
json_str = json.dumps(data)
json_str = json.dumps(data, indent=2) # 格式化
# 解码
data = json.loads(json_str)
# 文件操作
with open('data.json', 'w') as f:
json.dump(data, f)
with open('data.json') as f:
data = json.load(f)
七、re模块 - 正则表达式 #
python
import re
# 匹配
match = re.match(r'(\d+)', '123abc')
print(match.group(1)) # '123'
# 搜索
match = re.search(r'(\d+)', 'abc123')
print(match.group(1)) # '123'
# 查找所有
numbers = re.findall(r'\d+', 'a1b2c3') # ['1', '2', '3']
# 替换
result = re.sub(r'\d+', 'X', 'a1b2c3') # 'aXbXcX'
# 分割
parts = re.split(r'\s+', 'a b c') # ['a', 'b', 'c']
八、collections模块 #
python
from collections import Counter, defaultdict, OrderedDict
# Counter计数器
counter = Counter('hello')
print(counter) # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
# defaultdict默认值
d = defaultdict(list)
d['key'].append('value')
# OrderedDict有序字典
od = OrderedDict()
九、itertools模块 #
python
import itertools
# 无限迭代器
for i in itertools.count(10, 2):
if i > 20: break
print(i)
# 循环迭代
for item in itertools.cycle([1, 2, 3]):
break
# 排列组合
list(itertools.permutations([1, 2, 3], 2)) # 排列
list(itertools.combinations([1, 2, 3], 2)) # 组合
# 链接迭代器
list(itertools.chain([1, 2], [3, 4])) # [1, 2, 3, 4]
十、functools模块 #
python
from functools import reduce, partial, lru_cache
# reduce归约
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 10
# partial偏函数
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # 25
# lru_cache缓存
@lru_cache(maxsize=128)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
最后更新:2026-03-16