当前位置:首页 > 学习笔记 > 正文内容

Python 自动化办公实战 - 10 个效率翻倍的脚本

廖万里14小时前学习笔记3

# Python 自动化办公实战 - 10 个效率翻倍的脚本

> 重复性工作是效率的最大杀手。本文分享 10 个 Python 自动化办公脚本,帮你告别机械劳动,把时间花在更有价值的事情上。

---

📁 1. 批量重命名文件

面对几百个混乱命名的文件,手动改名简直是噩梦。用 Python 秒解决:

`python import os from pathlib import Path

def batch_rename(folder_path, prefix): """批量重命名文件夹中的文件""" folder = Path(folder_path) files = sorted(folder.glob('*')) for i, file in enumerate(files, 1): if file.is_file(): # 获取文件扩展名 ext = file.suffix # 新文件名 new_name = f"{prefix}_{i:03d}{ext}" # 重命名 file.rename(folder / new_name) print(f"重命名: {file.name} -> {new_name}")

# 使用示例 batch_rename('/Users/Downloads/图片', 'photo') `

使用场景:整理下载的图片、文档、视频等

---

📧 2. 自动发送邮件

定时发送日报、周报、通知邮件:

`python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime

def send_email(to_addr, subject, content, attachment_path=None): """发送邮件""" # 邮箱配置(以QQ邮箱为例) smtp_server = 'smtp.qq.com' smtp_port = 465 from_addr = 'your_email@qq.com' password = 'your_auth_code' # 授权码,非密码 # 创建邮件 msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject # 正文 msg.attach(MIMEText(content, 'plain', 'utf-8')) # 附件 if attachment_path: from email.mime.application import MIMEApplication with open(attachment_path, 'rb') as f: attachment = MIMEApplication(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=attachment_path.split('/')[-1]) msg.attach(attachment) # 发送 with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: server.login(from_addr, password) server.sendmail(from_addr, to_addr, msg.as_string()) print(f"邮件已发送: {to_addr}")

# 使用示例 send_email( 'boss@company.com', f'日报 - {datetime.now().strftime("%Y-%m-%d")}', '今日工作内容:\n1. 完成xxx\n2. 修复xxx' ) `

---

📊 3. Excel 数据合并

多个 Excel 文件合并成一个:

`python import pandas as pd from pathlib import Path

def merge_excel_files(folder_path, output_file): """合并多个Excel文件""" folder = Path(folder_path) all_data = [] for file in folder.glob('*.xlsx'): df = pd.read_excel(file) df['来源文件'] = file.name all_data.append(df) print(f"读取: {file.name} ({len(df)} 行)") # 合并 merged = pd.concat(all_data, ignore_index=True) # 保存 merged.to_excel(output_file, index=False) print(f"合并完成: {output_file} (共 {len(merged)} 行)") return merged

# 使用示例 merge_excel_files('/Users/Downloads/销售数据', '合并结果.xlsx') `

---

📸 4. 批量压缩图片

网站图片太大影响加载速度?批量压缩:

`python from PIL import Image from pathlib import Path

def compress_images(folder_path, quality=85, max_width=1920): """批量压缩图片""" folder = Path(folder_path) compressed_folder = folder / 'compressed' compressed_folder.mkdir(exist_ok=True) for file in folder.glob('*.jpg'): img = Image.open(file) # 调整大小 if img.width > max_width: ratio = max_width / img.width new_height = int(img.height * ratio) img = img.resize((max_width, new_height), Image.LANCZOS) # 保存压缩后的图片 output = compressed_folder / file.name img.save(output, 'JPEG', quality=quality, optimize=True) # 显示压缩效果 original_size = file.stat().st_size / 1024 # KB compressed_size = output.stat().st_size / 1024 ratio = (1 - compressed_size / original_size) * 100 print(f"{file.name}: {original_size:.1f}KB -> {compressed_size:.1f}KB (压缩 {ratio:.1f}%)")

# 使用示例 compress_images('/Users/Downloads/图片', quality=80) `

---

📄 5. PDF 转图片

需要提取 PDF 中的页面作为图片:

`python from pdf2image import convert_from_path from pathlib import Path

def pdf_to_images(pdf_path, output_folder, dpi=200): """PDF转图片""" output = Path(output_folder) output.mkdir(exist_ok=True) pdf_name = Path(pdf_path).stem images = convert_from_path(pdf_path, dpi=dpi) for i, image in enumerate(images, 1): output_path = output / f"{pdf_name}_page_{i}.png" image.save(output_path, 'PNG') print(f"保存: {output_path}") print(f"完成: 共 {len(images)} 页")

# 使用示例 pdf_to_images('/Users/Downloads/文档.pdf', '/Users/Downloads/PDF图片') `

---

🔔 6. 定时任务提醒

电脑自动弹窗提醒:

`python import time from datetime import datetime import subprocess

def desktop_notification(title, message): """发送桌面通知""" script = f''' display notification "{message}" with title "{title}" ''' subprocess.run(['osascript', '-e', script])

def reminder_loop(): """定时提醒循环""" reminders = [ ("09:00", "上班提醒", "新的一天开始了!"), ("10:30", "休息提醒", "站起来活动一下,保护眼睛"), ("12:00", "午餐提醒", "该吃午饭了"), ("14:00", "下午提醒", "下午工作开始"), ("17:00", "下班提醒", "快下班了,整理一下工作"), ] while True: now = datetime.now().strftime("%H:%M") for time_str, title, msg in reminders: if now == time_str: desktop_notification(title, msg) print(f"[{now}] {title}: {msg}") time.sleep(60) # 每分钟检查一次

# 使用示例 reminder_loop() `

---

📋 7. 剪贴板批量处理

批量处理剪贴板内容:

`python import pyperclip import time

def clipboard_processor(): """剪贴板处理器""" last_content = "" while True: content = pyperclip.paste() if content != last_content: last_content = content print(f"剪贴板内容: {content[:50]}...") # 自动处理:去除空格、转大写等 processed = content.strip().upper() if processed != content: pyperclip.copy(processed) print("已自动处理并更新剪贴板") time.sleep(0.5)

# 使用示例 clipboard_processor() `

---

🌐 8. 网站状态监控

监控网站是否正常访问:

`python import requests import time from datetime import datetime

def monitor_website(url, interval=60): """监控网站状态""" print(f"开始监控: {url}") while True: try: start_time = time.time() response = requests.get(url, timeout=10) elapsed = (time.time() - start_time) * 1000 # ms timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if response.status_code == 200: print(f"[{timestamp}] ✅ 正常 - 响应时间: {elapsed:.0f}ms") else: print(f"[{timestamp}] ⚠️ 异常 - 状态码: {response.status_code}") # 可以在这里添加邮件/微信通知 except Exception as e: print(f"[{timestamp}] ❌ 错误: {e}") time.sleep(interval)

# 使用示例 monitor_website('https://www.kkkliao.cn', interval=300) # 每5分钟检查 `

---

📝 9. Markdown 转 Word

批量转换 Markdown 文档:

`python import pypandoc from pathlib import Path

def markdown_to_word(folder_path, output_folder): """Markdown转Word""" input_folder = Path(folder_path) output = Path(output_folder) output.mkdir(exist_ok=True) for md_file in input_folder.glob('*.md'): output_file = output / f"{md_file.stem}.docx" try: pypandoc.convert_file( str(md_file), 'docx', outputfile=str(output_file) ) print(f"转换: {md_file.name} -> {output_file.name}") except Exception as e: print(f"失败: {md_file.name} - {e}")

# 使用示例 markdown_to_word('/Users/Documents/笔记', '/Users/Documents/Word') `

---

🗂️ 10. 文件自动分类

按文件类型自动分类整理:

`python from pathlib import Path import shutil

def organize_files(folder_path): """按类型整理文件""" folder = Path(folder_path) # 文件类型映射 type_mapping = { '图片': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'], '文档': ['.pdf', '.doc', '.docx', '.txt', '.md', '.xlsx', '.ppt'], '视频': ['.mp4', '.avi', '.mov', '.mkv', '.flv'], '音频': ['.mp3', '.wav', '.flac', '.m4a'], '压缩包': ['.zip', '.rar', '.7z', '.tar', '.gz'], '代码': ['.py', '.js', '.html', '.css', '.java', '.cpp'], } for file in folder.iterdir(): if file.is_file(): # 确定文件类型 ext = file.suffix.lower() file_type = '其他' for type_name, extensions in type_mapping.items(): if ext in extensions: file_type = type_name break # 移动文件 type_folder = folder / file_type type_folder.mkdir(exist_ok=True) shutil.move(str(file), type_folder / file.name) print(f"移动: {file.name} -> {file_type}/")

# 使用示例 organize_files('/Users/Downloads') `

---

💡 使用建议

1. 按需安装依赖pip install pandas openpyxl pillow pdf2image pyperclip pypandoc 2. 修改路径:将示例路径改为你的实际路径 3. 定时执行:配合系统定时任务或 cron 自动运行 4. 备份数据:批量操作前先备份重要文件

---

📊 效率提升对比

任务手动耗时Python 脚本效率提升
---------------------------------------
重命名 100 个文件10 分钟1 秒600x
合并 10 个 Excel15 分钟5 秒180x
压缩 50 张图片25 分钟10 秒150x
整理下载文件夹20 分钟2 秒600x
---

> 掌握这些脚本,让 Python 成为你最可靠的助手! > > 下一篇预告:Python 数据分析实战 - 从 Excel 到可视化图表

---

作者:廖万里 发布时间:2026年3月16日

本文链接:https://www.kkkliao.cn/?id=641 转载需授权!

分享到:

版权声明:本文由廖万里的博客发布,如需转载请注明出处。


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。