在当今的快节奏工作环境中,自动化不再是一种奢侈,而是提高效率和精确性的必需手段。Python 以其易于学习和强大的功能而闻名,成为实现各种自动化任务的理想选择。无论是数据处理、报告生成,还是日常的文件管理,一个简单但有效的 Python 脚本就能大幅减轻您的工作负担。本文旨在提供一套完整的 Python 自动化脚本方案,涵盖文件管理、Excel 处理、图片操作、系统任务及 PDF 编辑等核心场景,帮助您构建高效的自动化工作流。
环境准备
在开始之前,请确保您的开发环境已安装 Python 3.6+ 版本。以下脚本依赖第三方库,建议通过 pip 安装所需模块:
pip install pandas pillow psutil PyPDF2 requests
一、自动化文件管理
1. 整理目录中的文件
此脚本用于自动将指定目录下的文件按扩展名分类移动,保持目录整洁。
import os
from shutil import move
def sort_files(directory_path):
"""
遍历目录并按文件扩展名移动文件
:param directory_path: 目标目录路径
"""
if not os.path.exists(directory_path):
raise FileNotFoundError(f"目录不存在:{directory_path}")
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
if os.path.isfile(file_path):
if '.' in filename:
file_extension = filename.split('.')[-1]
destination_directory = os.path.join(directory_path, file_extension)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
try:
move(file_path, os.path.join(destination_directory, filename))
print(f"已移动:{filename} -> {file_extension}/")
except Exception as e:
print(f"移动失败 {filename}: {e}")
else:
print(f"跳过无扩展名文件:{filename}")
if __name__ == "__main__":
sort_files('your_directory_path')
说明:该函数接受一个目录路径作为参数。它遍历指定目录中的所有文件,检查每个文件是否是一个常规文件。对于有扩展名的文件,提取扩展名并创建对应目录(如果不存在),然后将文件移动过去。增加了异常处理以增强健壮性。
2. 移除空白的文档
清理目录下所有为空的文件夹,释放磁盘空间。
import os
def remove_empty_folders(directory_path):
"""
递归删除目录树中所有空文件夹
:param directory_path: 根目录路径
"""
for root, dirs, files in os.walk(directory_path, topdown=False):
for folder in dirs:
folder_path = os.path.join(root, folder)
if not os.listdir(folder_path):
try:
os.rmdir(folder_path)
print(f"已删除空目录:{folder_path}")
except OSError as e:
print(f"无法删除目录 {folder_path}: {e}")
remove_empty_folders('your_directory_path')
说明:使用 os.walk 遍历给定目录及其所有子目录。设置 topdown=False 确保在处理父目录前已处理完子目录。检查目录是否为空后使用 os.rmdir 删除。
3. 批量重命名文件
根据规则批量修改文件名,例如去除特定前缀或添加日期后缀。
import os
import re
def rename_files(directory_path, pattern, replacement):
"""
批量重命名文件
:param directory_path: 目录路径
:param pattern: 正则表达式匹配模式
:param replacement: 替换字符串
"""
count = 0
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
if os.path.isfile(file_path):
new_filename = re.sub(pattern, replacement, filename)
if new_filename != filename:
try:
os.rename(file_path, os.path.join(directory_path, new_filename))
count += 1
except FileExistsError:
print(f"目标文件已存在:{new_filename}")
print(f"共重命名 {count} 个文件")
rename_files('your_directory_path', r'old', 'new')
说明:利用正则表达式进行更灵活的重命名。支持复杂的匹配逻辑,比简单的字符串替换更强大。
二、Excel 办公自动化
1. 读取和写入数据
使用 Pandas 库高效处理 Excel 文件的读写操作。
import pandas as pd
def read_excel(file_path):
"""读取 Excel 文件返回 DataFrame"""
return pd.read_excel(file_path)
def write_to_excel(data, file_path):
"""将 DataFrame 数据写入 Excel 文件"""
df = pd.DataFrame(data) if not isinstance(data, pd.DataFrame) else data
df.to_excel(file_path, index=False, engine='openpyxl')
dataframe = read_excel('path_to_input_file.xlsx')
write_to_excel(dataframe, 'path_to_output_file.xlsx')
说明:read_excel 直接加载为 DataFrame 对象,便于后续分析。to_excel 中 index=False 避免写入行索引列,engine='openpyxl' 确保兼容性。
2. 合并多个工作表
将同一个 Excel 文件中的多个 Sheet 合并为一个。
import pandas as pd
def merge_sheets(file_path, output_file_path):
"""
合并 Excel 文件中的所有工作表
:param file_path: 输入文件路径
:param output_file_path: 输出文件路径
"""
xls = pd.ExcelFile(file_path)
all_dataframes = []
for sheet_name in xls.sheet_names:
sheet_df = pd.read_excel(xls, sheet_name)
all_dataframes.append(sheet_df)
merged_df = pd.concat(all_dataframes, ignore_index=True)
merged_df.to_excel(output_file_path, index=False)
print(f"合并完成,保存至:{output_file_path}")
merge_sheets('path_to_your_excel_file.xlsx', 'merged_output.xlsx')
说明:现代 Pandas 推荐使用 pd.concat 代替 df.append。代码遍历所有工作表名称,读取数据后合并,最后统一导出。
三、图片处理
1. 图片调整大小与裁剪
使用 Pillow 库进行基础图像变换。
from PIL import Image
def resize_image(input_path, output_path, width, height):
with Image.open(input_path) as image:
resized_image = image.resize((width, height), Image.Resampling.LANCZOS)
resized_image.save(output_path)
def crop_image(input_path, output_path, box):
"""
box: (left, upper, right, lower)
"""
with Image.open(input_path) as image:
cropped_image = image.crop(box)
cropped_image.save(output_path)
resize_image('input.jpg', 'resized.jpg', 800, 600)
crop_image('input.jpg', 'cropped.jpg', (100, 100, 400, 400))
说明:使用上下文管理器 with 确保文件句柄正确关闭。LANCZOS 提供更清晰的缩放效果。
2. 添加水印
为图片添加半透明文字水印,保护版权。
from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_path, output_path, watermark_text, font_size=36):
image = Image.open(input_path).convert("RGBA")
draw = ImageDraw.Draw(image)
try:
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
font = ImageFont.load_default()
bbox = draw.textbbox((0, 0), watermark_text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
x = (image.width - text_width) // 2
y = (image.height - text_height) // 2
draw.text((x, y), watermark_text, fill=(255, 255, 255, 128), font=font)
image.save(output_path)
add_watermark('input.jpg', 'watermarked.jpg', 'Copyright 2024')
说明:增加了字体加载的容错处理,并实现了简单的居中算法,使水印更美观。
3. 创建缩略图
批量生成图片缩略图,节省存储空间。
from PIL import Image
def create_thumbnail(input_path, output_path, size=(128, 128)):
with Image.open(input_path) as image:
image.thumbnail(size)
image.save(output_path)
create_thumbnail('input.jpg', 'thumbnail.jpg')
四、系统任务自动化
1. 进程管理与监控
使用 psutil 库查看和终止进程。
import psutil
def get_running_processes():
processes = []
for p in psutil.process_iter(['pid', 'name', 'username']):
try:
processes.append(p.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return processes
def kill_process_by_name(process_name):
for p in psutil.process_iter(['pid', 'name']):
try:
if process_name.lower() in p.info['name'].lower():
p.kill()
print(f"已终止进程:{p.info['name']} (PID: {p.info['pid']})")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
说明:增加了异常捕获,防止因权限不足或进程已结束导致脚本崩溃。
五、PDF 文件操作
1. 合并多个 PDF 文件
将多个 PDF 文档合并为一个。
import PyPDF2
def merge_pdfs(input_paths, output_path):
pdf_merger = PyPDF2.PdfMerger()
for path in input_paths:
try:
with open(path, 'rb') as f:
pdf_merger.append(f)
print(f"已添加:{path}")
except Exception as e:
print(f"添加失败 {path}: {e}")
with open(output_path, 'wb') as f:
pdf_merger.write(f)
print(f"合并完成:{output_path}")
merge_pdfs(['pdf1.pdf', 'pdf2.pdf'], 'merged.pdf')
2. PDF 密码保护
为 PDF 文件添加打开密码。
import PyPDF2
def add_password_protection(input_path, output_path, password):
with open(input_path, 'rb') as f:
reader = PyPDF2.PdfReader(f)
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.encrypt(password)
with open(output_path, 'wb') as out_f:
writer.write(out_f)
print("加密完成")
add_password_protection('input.pdf', 'protected.pdf', 'secure_password')
说明:更新了 API 调用方式,使用 PdfReader 和 pages 属性,符合新版 PyPDF2 规范。
六、邮件通知自动化
定期发送报表或状态通知。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_email(subject, content, to_addr, smtp_server, port, user, password):
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = Header(user, 'utf-8')
msg['To'] = Header(to_addr, 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(user, password)
server.sendmail(user, [to_addr], msg.as_string())
server.quit()
print("邮件发送成功")
except Exception as e:
print(f"发送失败:{e}")
send_email(
subject="日报通知",
content="今日任务已完成。",
to_addr="[email protected]",
smtp_server="smtp.example.com",
port=465,
user="[email protected]",
password="your_password"
)
七、网络数据抓取
简单的网页内容获取示例。
import requests
def fetch_webpage(url):
headers = {'User-Agent': 'Mozilla/5.0'}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print(f"请求失败:{e}")
return None
html = fetch_webpage('https://www.python.org')
if html:
print(f"获取到 {len(html)} 字节数据")
八、最佳实践与维护
- 错误处理:在生产环境中,务必使用
try-except 块包裹关键逻辑,记录日志以便排查问题。
- 敏感信息:密码、API Key 等敏感信息不应硬编码在脚本中,建议使用环境变量或配置文件管理。
- 调度执行:结合 Windows 任务计划程序或 Linux Crontab 定时运行脚本,实现真正的无人值守自动化。
- 资源释放:使用上下文管理器(
with 语句)打开文件和网络连接,确保资源及时释放。
- 版本控制:将脚本纳入 Git 管理,记录变更历史,便于团队协作和回滚。
结语
本文介绍了多种常见的 Python 自动化场景及对应的脚本实现。通过组合这些工具,您可以构建出适应自身业务需求的自动化工作流。建议在实际应用中根据具体需求调整代码逻辑,并持续优化性能。