第五篇: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 MIMETextmsg = 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方案:
from pdf2docx import Converterpdf_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 FileSystemEventHandlerclass 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
)讓腳本更健壯
討論:你最想自動化哪個辦公場景?歡迎留言!
如需其他方向的自動化案例(如網頁爬蟲、圖像處理等),可隨時提出!