20 个 Python 自动化脚本实战:文件管理与办公效率提升
使用 Python 实现各类办公与系统自动化的实用脚本方案。内容涵盖文件管理(分类整理、清空空目录、批量重命名)、Excel 数据处理(读写、多表合并)、图片处理(缩放、裁剪、水印、缩略图)、系统任务(进程监控与终止)、PDF 操作(合并、加密)以及新增的邮件发送和网络数据采集功能。文章提供了完整的代码示例和环境依赖说明,旨在帮助开发者通过脚本化手段提升工作效率,减少重复性劳动。

使用 Python 实现各类办公与系统自动化的实用脚本方案。内容涵盖文件管理(分类整理、清空空目录、批量重命名)、Excel 数据处理(读写、多表合并)、图片处理(缩放、裁剪、水印、缩略图)、系统任务(进程监控与终止)、PDF 操作(合并、加密)以及新增的邮件发送和网络数据采集功能。文章提供了完整的代码示例和环境依赖说明,旨在帮助开发者通过脚本化手段提升工作效率,减少重复性劳动。

在当今的快节奏工作环境中,自动化不再是一种奢侈,而是提高效率和精确性的必需手段。Python 以其易于学习和强大的功能而闻名,成为实现各种自动化任务的理想选择。无论是数据处理、报告生成,还是日常的文件管理,一个简单但有效的 Python 脚本就能大幅减轻您的工作负担。
在开始之前,请确保已安装 Python 3.6+ 版本,并安装以下第三方库:
pip install pandas openpyxl pillow psutil PyPDF2 requests beautifulsoup4
该脚本可以自动将指定目录下的文件按扩展名分类移动。
import os
from shutil import move
def sort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, 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)
move(os.path.join(directory_path, filename),
os.path.join(destination_directory, filename))
# 调用函数,替换路径
if __name__ == '__main__':
sort_files('your_directory_path')
说明: 函数遍历指定目录中的所有文件,提取扩展名创建对应子目录并移动文件。
清理目录下所有为空的文件夹,保持目录整洁。
import os
def remove_empty_folders(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):
os.rmdir(folder_path)
if __name__ == '__main__':
remove_empty_folders('your_directory_path')
说明: 使用 os.walk 从底层向上遍历,确保删除空目录前已处理完子目录。
根据规则批量修改文件名,例如去除特定前缀或后缀。
import os
def rename_files(directory_path, old_name, new_name):
for filename in os.listdir(directory_path):
if old_name in filename:
new_filename = filename.replace(old_name, new_name)
os.rename(os.path.join(directory_path, filename),
os.path.join(directory_path, new_filename))
if __name__ == '__main__':
# 示例:将 'old_' 替换为 'new_'
rename_files('your_directory_path', 'old_', 'new_')
利用 pandas 库高效处理 Excel 文件的读写操作。
import pandas as pd
def read_excel(file_path):
df = pd.read_excel(file_path)
return df
def write_to_excel(data, file_path):
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)
if __name__ == '__main__':
dataframe = read_excel('path_to_your_input_file.xlsx')
write_to_excel(dataframe, 'path_to_your_output_file.xlsx')
说明: index=False 参数表示在输出的 Excel 文件中不包括行索引,使表格更美观。
将同一个 Excel 文件中的多个 Sheet 合并到一个新的文件中。
import pandas as pd
def merge_sheets(file_path, output_file_path):
xls = pd.ExcelFile(file_path)
df = pd.DataFrame()
for sheet_name in xls.sheet_names:
sheet_df = pd.read_excel(xls, sheet_name)
df = pd.concat([df, sheet_df], ignore_index=True)
df.to_excel(output_file_path, index=False)
if __name__ == '__main__':
merge_sheets('path_to_your_excel_file.xlsx', 'output_merged.xlsx')
说明: 使用 pd.concat 替代 deprecated 的 append 方法,性能更好且符合新版 Pandas 规范。
使用 Pillow 库进行基础图片编辑。
from PIL import Image
def resize_image(input_path, output_path, width, height):
image = Image.open(input_path)
resized_image = image.resize((width, height), Image.Resampling.LANCZOS)
resized_image.save(output_path)
def crop_image(input_path, output_path, left, top, right, bottom):
image = Image.open(input_path)
cropped_image = image.crop((left, top, right, bottom))
cropped_image.save(output_path)
if __name__ == '__main__':
resize_image('input.jpg', 'resized.jpg', 800, 600)
crop_image('input.jpg', 'cropped.jpg', 100, 100, 400, 400)
为图片添加半透明文字水印,保护版权。
from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_path, output_path, watermark_text):
image = Image.open(input_path).convert('RGBA')
draw = ImageDraw.Draw(image)
try:
font = ImageFont.truetype('arial.ttf', 36)
except IOError:
font = ImageFont.load_default()
draw.text((10, 10), watermark_text, fill=(255, 255, 255, 128), font=font)
image.save(output_path)
if __name__ == '__main__':
add_watermark('input.jpg', 'watermarked.jpg', 'Copyright Text')
批量生成图片缩略图,节省存储空间。
from PIL import Image
def create_thumbnail(input_path, output_path, size=(128, 128)):
image = Image.open(input_path)
image.thumbnail(size)
image.save(output_path)
if __name__ == '__main__':
create_thumbnail('input.jpg', 'thumbnail.jpg')
查看当前运行进程并强制结束指定名称的进程。
import psutil
def get_running_processes():
return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]
def kill_process_by_name(process_name):
for p in psutil.process_iter(['pid', 'name', 'username']):
try:
if p.info['name'] == process_name:
p.kill()
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
if __name__ == '__main__':
print(get_running_processes())
# kill_process_by_name('process_name_here')
将多个 PDF 文件合并为一个。
import PyPDF2
def merge_pdfs(input_paths, output_path):
pdf_merger = PyPDF2.PdfMerger()
for path in input_paths:
with open(path, 'rb') as f:
pdf_merger.append(f)
with open(output_path, 'wb') as f:
pdf_merger.write(f)
if __name__ == '__main__':
input_pdf_paths = ['pdf1.pdf', 'pdf2.pdf']
merge_pdfs(input_pdf_paths, 'merged.pdf')
为 PDF 文件设置打开密码。
import PyPDF2
def add_password_protection(input_path, output_path, password):
with open(input_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
pdf_writer = PyPDF2.PdfWriter()
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
pdf_writer.add_page(page)
pdf_writer.encrypt(password)
with open(output_path, 'wb') as output_file:
pdf_writer.write(output_file)
if __name__ == '__main__':
add_password_protection('input.pdf', 'protected.pdf', 'your_password')
使用 smtplib 自动发送邮件通知。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_addr, from_addr, smtp_server, port, user, pwd):
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg.attach(MIMEText(body, 'html'))
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(user, pwd)
server.send_message(msg)
server.quit()
if __name__ == '__main__':
send_email(
subject='Test Report',
body='<h1>Hello</h1>',
to_addr='[email protected]',
from_addr='[email protected]',
smtp_server='smtp.example.com',
port=587,
user='user',
pwd='password'
)
使用 requests 和 BeautifulSoup 获取网页标题。
import requests
from bs4 import BeautifulSoup
def scrape_title(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string if soup.title else 'No Title'
return title
if __name__ == '__main__':
print(scrape_title('https://www.python.org'))
本文介绍了多种常用的 Python 自动化脚本场景,涵盖文件管理、Office 处理、图像处理、系统维护及网络交互。通过模块化设计,这些脚本可灵活组合以适应不同需求。在实际应用中,建议增加异常处理机制(try-except),并定期备份重要数据。掌握这些基础脚本后,开发者可进一步探索 Selenium 进行浏览器自动化,或使用 Airtest 进行游戏/应用测试,从而构建更复杂的自动化工作流。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online