每天被重复性工作占用大量时间?其实,很多任务都可以用 Python 脚本自动完成。本文整理了 9 个最实用的 Python 自动化场景,每个都附带可直接复制运行的代码,帮你从繁琐操作中解放出来。
Python 最大的优势之一,就是能用极少的代码完成大量重复性工作。无论是整理文件、发送邮件、监控网站,还是处理图片视频,几乎都有现成的库可以调用。
下面这 9 个脚本,都是从真实工作场景中提炼出来的。你可以直接复制代码,根据自己的需求稍作修改就能跑起来。
场景:每天需要发送固定格式的邮件,比如日报、通知、提醒。
import smtplibfrom email.mime.text import MIMETextimport ossubject = "自动邮件"body = "这是一封用 Python 发送的自动邮件"to_email = "recipient@example.com"from_email = "sender@example.com"# 密码从环境变量读取,不要硬编码password = os.environ.get("EMAIL_PASSWORD")msg = MIMEText(body)msg["Subject"] = subjectmsg["From"] = from_emailmsg["To"] = to_emailtry: server = smtplib.SMTP_SSL("smtp.example.com", 465) server.login(from_email, password) server.sendmail(from_email, to_email, msg.as_string())print("邮件发送成功")except Exception as e:print(f"发送失败:{e}")finally: server.quit()注意点:
.env 文件中,不要写死在代码里。SMTP_SSL 或 starttls,避免明文传输。场景:下载目录堆积如山,想按文件类型自动分类。
import osimport shutilfrom pathlib import Pathsrc_dir = Path("/path/to/source/directory")dst_dir = Path("/path/to/destination/directory")for file in src_dir.iterdir():if file.is_file() andnot file.name.startswith("."): ext = file.suffix.lower() or"其他" target_folder = dst_dir / ext target_folder.mkdir(parents=True, exist_ok=True) shutil.move(str(file), str(target_folder / file.name))注意点:
pathlib 比 os.path 更 Pythonic。. 开头),避免误移动系统文件。shutil.move 换成 shutil.copy2。场景:运营账号需要定时发布内容。
import tweepyclient = tweepy.Client( bearer_token="your_bearer_token", consumer_key="your_api_key", consumer_secret="your_api_secret", access_token="your_access_token", access_token_secret="your_access_token_secret")response = client.create_tweet(text="这是一条用 Python 发送的自动推文")print(f"推文已发布:{response.data['id']}")注意点:
tweepy 库,OAuth 流程已经封装好了。场景:每天把数据写入 Google Sheets 或 Excel 表格。
import gspreadfrom google.oauth2.service_account import Credentialsscopes = ["https://www.googleapis.com/auth/spreadsheets"]creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)client = gspread.authorize(creds)sheet = client.open_by_key("your_spreadsheet_id").sheet1sheet.update("A1:B2", [[1, 2], [3, 4]])注意点:
credentials.json。gspread 比原生的 googleapiclient 更简洁,代码量少很多。openpyxl 库,不需要联网。场景:想第一时间知道某个网站是不是宕机了。
import requestsimport timeurl = "https://www.example.com"try: response = requests.get(url, timeout=5)if200 <= response.status_code < 300:print(f"✅ {url} 正常访问")else:print(f"⚠️ {url} 返回状态码:{response.status_code}")except requests.RequestException as e:print(f"❌ {url} 访问失败:{e}")注意点:
timeout,避免某个网站卡住导致脚本 hanging。200。schedule 库和消息推送,就能做成一个简易监控告警系统。场景:定期把重要文件夹打包备份。
import shutilfrom datetime import datetimefrom pathlib import Pathsrc_dir = Path("/path/to/source/directory")backup_dir = Path("/path/to/backup/directory")backup_dir.mkdir(parents=True, exist_ok=True)timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")backup_path = backup_dir / f"backup_{timestamp}"shutil.make_archive(str(backup_path), "zip", str(src_dir))print(f"备份完成:{backup_path}.zip")注意点:
shutil.make_archive 可以生成 zip、tar、gztar 等格式。rdiff-backup 或云同步服务。场景:每天从数据生成 CSV 或 Excel 报表。
import pandas as pdfrom datetime import datetimesales_data = {"Date": ["2025-07-01", "2025-07-02", "2025-07-03"],"Sales": [100, 200, 300]}df = pd.DataFrame(sales_data)df["Date"] = pd.to_datetime(df["Date"])report_name = f"sales_report_{datetime.now().strftime('%Y%m%d')}.csv"df.to_csv(report_name, index=False)print(f"报表已生成:{report_name}")注意点:
pd.to_datetime 把日期列转成正确格式,方便后续分析。df.to_excel 生成 Excel 文件,并添加样式。场景:需要把一批图片统一调整尺寸或转换格式。
from PIL import Imagefrom pathlib import Pathinput_dir = Path("./images")output_dir = Path("./resized")output_dir.mkdir(exist_ok=True)for image_file in input_dir.glob("*.jpg"):with Image.open(image_file) as img: img.thumbnail((800, 800)) output_path = output_dir / f"{image_file.stem}_resized.jpg" img.save(output_path, quality=85)print(f"已处理:{output_path}")注意点:
thumbnail 会保持宽高比,resize 不会,按需求选择。glob 遍历文件夹。quality 参数控制文件大小。场景:从长视频中截取精彩片段。
from moviepy.editor import VideoFileClipclip = VideoFileClip("input_video.mp4")trimmed_clip = clip.subclip(5, 30) # 截取第 5 秒到第 30 秒trimmed_clip.write_videofile("output_video.mp4")注意点:
moviepy 适合入门和中小规模处理,API 非常直观。FFmpeg 会更快,可以配合 subprocess 调用。上面的脚本都是最小可用版本,真正用到生产环境或日常工作中,建议再加三件套:
argparsepython-dotenv | ||
try/exceptlogging | ||
schedulecron |
把这三个基础能力补上,你的自动化脚本就从“玩具”变成“工具”了。

长按或扫描下方二维码,免费获取 Python公开课和大佬打包整理的几百G的学习资料,内容包含但不限于Python电子书、教程、项目接单、源码等等
▲扫描二维码-免费领取
推荐阅读
点击 阅读原文了解更多