Python自动化办公

第五篇:Python自动化办公:10行代码搞定重复性工作

适合读者 :职场人士、数据分析师 | 阅读时长:12分钟


引言

每天重复处理Excel、PDF或邮件?Python可以帮你自动化这些枯燥任务,节省90%的时间。本文通过实际案例,展示如何用10行以内的代码提升办公效率。


1. 批量处理Excel文件

场景 :合并多个Excel表格中的销售数据。
传统方法 :手动复制粘贴 → 容易出错 + 耗时。
Python方案

python 复制代码
import pandas as pd
import glob

# 读取所有Excel文件并合并
files = glob.glob("sales_*.xlsx")  # 匹配所有以sales_开头的文件
df = pd.concat([pd.read_excel(f) for f in files])
df.to_excel("combined_sales.xlsx", index=False)  # 输出合并后的文件

效果:3秒完成原本需要1小时的工作。


2. 自动发送邮件(带附件)

场景 :每周定时发送报告给团队。
传统方法 :手动编辑邮件 + 添加附件 → 枯燥且易忘。
Python方案

python 复制代码
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart()
msg["From"] = "your_email@example.com"
msg["To"] = "team@example.com"
msg["Subject"] = "本周销售报告"
msg.attach(MIMEText("请查收附件中的最新数据。", "plain"))

# 添加附件
with open("report.pdf", "rb") as f:
    attachment = MIMEText(f.read(), "base64", "utf-8")
    attachment["Content-Disposition"] = 'attachment; filename="report.pdf"'
    msg.attach(attachment)

# 发送邮件(需配置SMTP服务器)
server = smtplib.SMTP("smtp.example.com", 587)
server.login("your_email@example.com", "password")
server.send_message(msg)
server.quit()

安全提示 :建议使用keyring库存储密码,而非硬编码。


3. PDF批量转Word

场景 :客户提供PDF合同,需转为Word编辑。
传统方法 :使用付费软件逐个转换 → 费钱费时。
Python方案

python 复制代码
from pdf2docx import Converter

pdf_files = ["contract1.pdf", "contract2.pdf"]
for pdf in pdf_files:
    docx_file = pdf.replace(".pdf", ".docx")
    cv = Converter(pdf)
    cv.convert(docx_file, start=0, end=None)
    cv.close()

依赖库pip install pdf2docx
注意:复杂排版可能需微调。


4. 监控文件夹 + 自动备份

场景 :实时备份重要文件到云端。
传统方法 :手动拖拽到网盘 → 容易遗漏。
Python方案

python 复制代码
import shutil
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class BackupHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory:  # 只处理文件
            shutil.copy2(event.src_path, "/cloud_backup/")

observer = Observer()
observer.schedule(BackupHandler(), path="/important_files/")
observer.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

扩展:可集成Google Drive/Dropbox API实现真·云端备份。


5. 微信消息自动化(防撤回存档)

场景 :保存重要群聊中的撤回消息。
技术栈itchat + 正则表达式
代码片段

python 复制代码
import itchat
import re

@itchat.msg_register(itchat.content.TEXT)
def save_recalled(msg):
    if "撤回了一条消息" in msg["Text"]:
        recalled = re.search(r'"(.+?)"', msg["Text"]).group(1)
        with open("recalled.txt", "a") as f:
            f.write(f"{msg['FromUserName']} 撤回:{recalled}\n")

itchat.auto_login(hotReload=True)
itchat.run()

注意:需遵守平台使用规范,避免滥用。


结语

Python自动化不是程序员的专利。掌握这些脚本,你将成为办公室的效率明星。
下一步

  1. 尝试将脚本设置为定时任务(如用cron或Windows任务计划程序)
  2. 学习错误处理(try/except)让脚本更健壮

讨论:你最想自动化哪个办公场景?欢迎留言!


如需其他方向的自动化案例(如网页爬虫、图像处理等),可随时提出!

相关推荐
iCxhust1 小时前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo2 小时前
ES6笔记2
开发语言·前端·javascript
G皮T3 小时前
【人工智能】ChatGPT、DeepSeek-R1、DeepSeek-V3 辨析
人工智能·chatgpt·llm·大语言模型·deepseek·deepseek-v3·deepseek-r1
九年义务漏网鲨鱼3 小时前
【大模型学习 | MINIGPT-4原理】
人工智能·深度学习·学习·语言模型·多模态
emplace_back3 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk3 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
元宇宙时间3 小时前
Playfun即将开启大型Web3线上活动,打造沉浸式GameFi体验生态
人工智能·去中心化·区块链
开发者工具分享3 小时前
文本音频违规识别工具排行榜(12选)
人工智能·音视频
萧曵 丶3 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust