Python标准库包含了很多实用的模块,这些模块能帮助我们完成各种常见任务。学会使用标准库,可以大大提高编程效率。
os模块提供了与操作系统交互的各种功能。
import os
# 获取当前工作目录
current_dir = os.getcwd()
print("当前目录:", current_dir)
# 列出目录内容
files = os.listdir(".")
print("当前目录文件:", files)
# 创建新目录
os.mkdir("new_folder")
# 删除文件
if os.path.exists("temp.txt"):
os.remove("temp.txt")
# 检查路径类型
print("是否是文件:", os.path.isfile("example.py"))
print("是否是目录:", os.path.isdir("new_folder"))shutil模块提供了更便捷的文件操作功能。
import shutil
# 复制文件
shutil.copy("source.txt", "backup.txt")
# 复制整个目录
shutil.copytree("source_dir", "backup_dir")
# 移动文件或目录
shutil.move("old_location.txt", "new_location.txt")
# 删除目录(包括所有内容)
shutil.rmtree("directory_to_delete")sys模块提供与Python解释器相关的功能。
import sys
# 获取命令行参数
print("脚本名:", sys.argv[0])
print("所有参数:", sys.argv)
# Python解释器信息
print("Python版本:", sys.version)
print("系统平台:", sys.platform)
# 标准输入输出
sys.stdout.write("这是标准输出\n")
sys.stderr.write("这是错误输出\n")
# 退出程序
if len(sys.argv) < 2:
print("需要提供参数")
sys.exit(1)import time
# 获取当前时间戳
timestamp = time.time()
print("当前时间戳:", timestamp)
# 暂停程序
print("开始等待...")
time.sleep(2) # 暂停2秒
print("等待结束")
# 格式化时间
local_time = time.localtime()
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("格式化时间:", formatted)from datetime import datetime, date, timedelta
# 当前日期时间
now = datetime.now()
print("当前时间:", now)
# 特定日期
birthday = date(2024, 12, 25)
print("圣诞节:", birthday)
# 日期计算
tomorrow = date.today() + timedelta(days=1)
next_week = datetime.now() + timedelta(weeks=1)
print("明天:", tomorrow)
print("下周:", next_week)
# 日期格式化
formatted = now.strftime("%Y年%m月%d日 %H时%M分")
print("中文格式:", formatted)import math
# 基本数学运算
print("圆周率:", math.pi)
print("自然常数:", math.e)
# 三角函数
angle = math.radians(45) # 角度转弧度
print("sin(45°):", math.sin(angle))
# 对数和指数
print("2的10次方:", math.pow(2, 10))
print("100的自然对数:", math.log(100))
# 取整函数
print("向上取整:", math.ceil(3.2))
print("向下取整:", math.floor(3.8))
print("四舍五入:", round(3.6))import random
# 生成随机数
print("0-1之间的随机数:", random.random())
print("1-10的随机整数:", random.randint(1, 10))
# 从序列中随机选择
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
print("随机水果:", random.choice(fruits))
# 随机抽样
numbers = list(range(1, 101))
sample = random.sample(numbers, 5)
print("随机抽样:", sample)
# 打乱序列顺序
cards = ["红桃A", "黑桃K", "方块Q", "梅花J"]
random.shuffle(cards)
print("洗牌后:", cards)# 字符串常用方法
text = " Python编程教程 "
print("去除空格:", text.strip())
print("转为大写:", text.upper())
print("替换内容:", text.replace("Python", "Java"))
print("分割字符串:", "a,b,c".split(","))
print("连接字符串:", "-".join(["2024", "01", "01"]))
# 字符串格式化
name = "小明"
age = 20
message = "{}今年{}岁".format(name, age)
print(message)
# f-string (Python 3.6+)
message = f"{name}今年{age}岁"
print(message)import re
# 查找匹配
text = "我的电话是138-0013-8000,邮箱是test@fly63.com"
phone_pattern = r'\d{3}-\d{4}-\d{4}'
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print("找到的电话:", re.findall(phone_pattern, text))
print("找到的邮箱:", emails)
# 替换文本
new_text = re.sub(phone_pattern, "***-****-****", text)
print("替换后:", new_text)
# 分割字符串
data = "苹果,香蕉;橙子|葡萄"
items = re.split(r'[,;|]', data)
print("分割结果:", items)import glob
# 查找所有Python文件
python_files = glob.glob("*.py")
print("Python文件:", python_files)
# 递归查找
all_text_files = glob.glob("**/*.txt", recursive=True)
print("所有文本文件:", all_text_files)
# 多种模式匹配
images = glob.glob("*.jpg") + glob.glob("*.png") + glob.glob("*.gif")
print("图片文件:", images)import os
# 路径拼接
full_path = os.path.join("folder", "subfolder", "file.txt")
print("完整路径:", full_path)
# 路径分割
directory, filename = os.path.split("/home/user/document.txt")
print("目录:", directory)
print("文件名:", filename)
# 获取文件扩展名
name, ext = os.path.splitext("image.jpg")
print("文件名:", name)
print("扩展名:", ext)
# 获取绝对路径
abs_path = os.path.abspath("relative/path")
print("绝对路径:", abs_path)import json
# Python对象转JSON
data = {
"name": "张三",
"age": 25,
"courses": ["数学", "英语", "编程"],
"is_student": True
}
json_string = json.dumps(data, ensure_ascii=False, indent=2)
print("JSON字符串:")
print(json_string)
# JSON转Python对象
parsed_data = json.loads(json_string)
print("解析后的数据:", parsed_data)
# 读写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_data = json.load(f)
print("从文件加载:", loaded_data)from urllib.request import urlopen
from urllib.parse import urlencode
import json
def get_webpage(url):
"""获取网页内容"""
try:
with urlopen(url) as response:
content = response.read().decode('utf-8')
return content
except Exception as e:
print(f"访问失败: {e}")
return None
# 使用示例
# content = get_webpage("https://www.fly63.com")
# if content:
# print("网页内容长度:", len(content))import zlib
import gzip
# 使用zlib压缩
original_data = b"这是一段需要压缩的文本数据" * 100
compressed = zlib.compress(original_data)
decompressed = zlib.decompress(compressed)
print("原始大小:", len(original_data))
print("压缩后:", len(compressed))
print("解压后相等:", original_data == decompressed)
# 使用gzip读写压缩文件
with gzip.open("data.txt.gz", "wt", encoding="utf-8") as f:
f.write("这是压缩的文本内容")
with gzip.open("data.txt.gz", "rt", encoding="utf-8") as f:
content = f.read()
print("读取的压缩内容:", content)import timeit
# 测试两种方法的性能
code1 = """
result = []
for i in range(1000):
result.append(i * 2)
"""
code2 = """
result = [i * 2 for i in range(1000)]
"""
time1 = timeit.timeit(code1, number=1000)
time2 = timeit.timeit(code2, number=1000)
print("循环方法时间:", time1)
print("列表推导式时间:", time2)
print("列表推导式更快:", time2 < time1)import os
import shutil
from datetime import datetime
def backup_files(source_dir, backup_dir):
"""备份目录中的文件"""
if not os.path.exists(source_dir):
print("源目录不存在")
return False
# 创建带时间戳的备份目录
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(backup_dir, f"backup_{timestamp}")
try:
# 复制目录
shutil.copytree(source_dir, backup_path)
print(f"备份成功: {backup_path}")
return True
except Exception as e:
print(f"备份失败: {e}")
return False
# 使用示例
backup_files("./documents", "./backups")import re
from collections import Counter
def analyze_log_file(log_file):
"""分析日志文件"""
if not os.path.exists(log_file):
print("日志文件不存在")
return
ip_pattern = r'\d+\.\d+\.\d+\.\d+'
ips = []
with open(log_file, 'r', encoding='utf-8') as f:
for line in f:
# 提取IP地址
match = re.search(ip_pattern, line)
if match:
ips.append(match.group())
# 统计IP出现次数
ip_count = Counter(ips)
print("访问最多的IP地址:")
for ip, count in ip_count.most_common(5):
print(f" {ip}: {count}次")
print(f"总访问次数: {len(ips)}")
print(f"独立IP数量: {len(ip_count)}")
# 使用示例
analyze_log_file("access.log")查阅官方文档:Python官方文档是最准确的学习资源
多动手实践:实际编写代码来熟悉各个模块
查看模块帮助:使用help(模块名)查看详细说明
阅读源码:查看标准库源码学习编程技巧
关注常用模块:重点掌握os、sys、datetime、json等常用模块
掌握Python标准库的使用,能够让你在开发过程中事半功倍。这些模块经过充分测试和优化,是Python编程的重要工具。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!