马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
第五篇:Python主动化办公:10行代码搞定重复性工作
恰当读者:职场人士、数据分析师 | 阅读时长:12分钟
弁言
每天重复处置惩罚Excel、PDF或邮件?Python可以帮你主动化这些枯燥任务,节省90%的时间。本文通过现实案例,展示怎样用10行以内的代码提升办公服从。
1. 批量处置惩罚Excel文件
场景:归并多个Excel表格中的贩卖数据。
传统方法:手动复制粘贴 → 轻易堕落 + 耗时。
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方案:- import smtplib
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- msg = MIMEMultipart()
- msg["From"] = "[email protected]"
- msg["To"] = "[email protected]"
- 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("[email protected]", "password")
- server.send_message(msg)
- server.quit()
复制代码 安全提示:发起使用keyring库存储密码,而非硬编码。
3. PDF批量转Word
场景:客户提供PDF条约,需转为Word编辑。
传统方法:使用付费软件逐个转换 → 费钱费时。
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方案:- 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 + 正则表达式
代码片断:- 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主动化不是步调员的专利。把握这些脚本,你将成为办公室的服从明星。
下一步:
- 尝试将脚本设置为定时任务(如用cron或Windows任务操持步调)
- 学习错误处置惩罚(try/except)让脚本更健壮
讨论:你最想主动化哪个办公场景?欢迎留言!
如需其他方向的主动化案例(如网页爬虫、图像处置惩罚等),可随时提出!
|