Python自动化脚本实战:5个让你工作效率翻倍的实用案例

今天 10阅读

Python之所以成为2026年最受欢迎的编程语言,很大原因在于它的自动化能力。

前置准备

需要安装:pip install openpyxl pandas requests schedule pillow

案例1:批量处理Excel文件

import pandas as pd
import os

def merge_excel(folder_path, output_file):
    all_data = []
    for file in os.listdir(folder_path):
        if not file.endswith(".xlsx"):
            continue
        df = pd.read_excel(os.path.join(folder_path, file))
        df["来源文件"] = file
        all_data.append(df)
    result = pd.concat(all_data, ignore_index=True)
    result.to_excel(output_file, index=False)

merge_excel("./数据/", "汇总结果.xlsx")

案例2:自动整理下载文件夹

import os, shutil

def organize_folder(path):
    types = {"图片": [".jpg",".png",".gif"], "文档": [".pdf",".docx",".txt"], "安装包": [".exe",".dmg",".apk"]}
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if not os.path.isfile(file_path): continue
        ext = os.path.splitext(file)[1].lower()
        for folder, exts in types.items():
            if ext in exts:
                target = os.path.join(path, folder)
                os.makedirs(target, exist_ok=True)
                shutil.move(file_path, os.path.join(target, file))
                break

organize_folder("/Downloads")

案例3:定时发送工作日报

import smtplib, schedule, time
from email.mime.text import MIMEText

def send_report():
    msg = MIMEText("工作日报内容", "plain", "utf-8")
    msg["Subject"] = "工作日报"
    msg["From"] = "you@example.com"
    msg["To"] = "team@company.com"
    with smtplib.SMTP_SSL("smtp.qq.com", 465) as s:
        s.login("you@example.com", "授权码")
        s.send_message(msg)

schedule.every().day.at("17:00").do(send_report)
while True:
    schedule.run_pending()
    time.sleep(60)

案例4:网页数据抓取

import requests
from bs4 import BeautifulSoup

def get_price(url):
    resp = requests.get(url, headers={"User-Agent":"Mozilla/5.0"}, timeout=10)
    soup = BeautifulSoup(resp.text, "html.parser")
    price = soup.select_one(".price")
    return price.text.strip() if price else "未找到"

print(get_price("https://example.com/product/123"))

案例5:图片批量加水印

from PIL import Image, ImageDraw, ImageFont
import os

def add_watermark(input_dir, output_dir, text="极派博客"):
    os.makedirs(output_dir, exist_ok=True)
    for file in os.listdir(input_dir):
        if not file.endswith((".jpg",".png")): continue
        img = Image.open(os.path.join(input_dir, file))
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype("simhei.ttf", 36)
        w, h = img.size
        draw.text((w-200, h-50), text, font=font, fill=(255,255,255,128))
        img.save(os.path.join(output_dir, file))

add_watermark("./原图/", "./加水印/")

掌握这5个案例,你已经能解决90%的日常自动化需求。记住:任何你重复做3次以上的事情,都值得写个脚本自动化。

文章版权声明:除非注明,否则均为极派博客原创文章,转载或复制请以超链接形式并注明出处。
取消
微信二维码
微信二维码
支付宝二维码