sudo-iのBlog

  • 🍟首页
  • 🍊目录
    • 技术分享
    • vps教程
    • 软件分享
    • 干货分享
  • 🍎链接
  • 🍓工具
    • 🌽IP路由追踪
    • 域名被墙检测
    • KMS激活
    • 域名whois查询
  • 🍕联系
  • 🍌登录
Sudo-i
关注互联网,生活,音乐,乐此不疲
  1. 首页
  2. 干货分享
  3. 正文

Python 自动化脚本:提升工作效率的 10 个实用案例

28 2 月, 2026 11点热度 0人点赞 0条评论

引言

在数字化时代,自动化已成为提升工作效率的关键。Python 凭借其简洁的语法和丰富的库生态,成为自动化脚本开发的首选语言。本文将通过 10 个实用案例,展示如何使用 Python 自动化日常任务,让你从重复性工作中解放出来。

一、文件批量重命名

处理大量文件时,手动重命名既耗时又容易出错。使用 Python 可以轻松实现批量重命名:

import os
from datetime import datetime

def batch_rename_files(directory, prefix="backup"):
    """批量重命名文件,添加前缀和时间戳"""
    timestamp = datetime.now().strftime("%Y%m%d")
    
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            name, ext = os.path.splitext(filename)
            new_name = f"{prefix}_{timestamp}_{name}{ext}"
            os.rename(
                os.path.join(directory, filename),
                os.path.join(directory, new_name)
            )
            print(f"重命名:{filename} → {new_name}")

# 使用示例
batch_rename_files("/path/to/your/folder")

二、自动备份重要文件

定期备份是数据安全的基础。以下脚本自动备份指定目录到备份文件夹:

import shutil
from pathlib import Path

def auto_backup(source_dir, backup_dir, keep_days=7):
    """自动备份文件并清理旧备份"""
    from datetime import datetime, timedelta
    
    backup_name = f"backup_{datetime.now().strftime("%Y%m%d_%H%M%S")}"
    backup_path = Path(backup_dir) / backup_name
    
    # 创建备份
    shutil.copytree(source_dir, backup_path)
    print(f"备份完成:{backup_path}")
    
    # 清理超过指定天数的旧备份
    cutoff = datetime.now() - timedelta(days=keep_days)
    for old_backup in Path(backup_dir).glob("backup_*"):
        if old_backup.stat().st_mtime < cutoff.timestamp():
            shutil.rmtree(old_backup)
            print(f"清理旧备份:{old_backup}")

# 使用示例
auto_backup("/home/user/documents", "/backup/location")

三、网页内容监控与通知

监控网页变化并在发现更新时发送通知:

import requests
import hashlib
import time

def monitor_webpage(url, check_interval=3600):
    """监控网页内容变化"""
    last_hash = None
    
    while True:
        try:
            response = requests.get(url, timeout=10)
            current_hash = hashlib.md5(response.content).hexdigest()
            
            if last_hash and current_hash != last_hash:
                print(f"⚠️ 网页内容已更新!{url}")
                # 这里可以添加邮件或消息通知
            
            last_hash = current_hash
            print(f"✓ 检查完成:{url}")
            
        except Exception as e:
            print(f"检查失败:{e}")
        
        time.sleep(check_interval)

# 使用示例
monitor_webpage("https://example.com/news")

四、Excel 数据自动处理

使用 openpyxl 库自动化 Excel 数据处理:

from openpyxl import Workbook, load_workbook

def process_excel_data(input_file, output_file):
    """读取 Excel 数据,进行处理后保存"""
    wb = load_workbook(input_file)
    ws = wb.active
    
    # 添加新列:计算总价
    ws.cell(row=1, column=4, value="总价")
    
    for row in range(2, ws.max_row + 1):
        price = ws.cell(row=row, column=2).value
        quantity = ws.cell(row=row, column=3).value
        total = price * quantity if price and quantity else 0
        ws.cell(row=row, column=4, value=total)
    
    wb.save(output_file)
    print(f"处理完成,已保存到:{output_file}")

# 使用示例
process_excel_data("sales.xlsx", "sales_processed.xlsx")

五、自动发送邮件报告

定时生成并发送数据报告邮件:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email_report(recipients, subject, content):
    """发送 HTML 格式的报告邮件"""
    msg = MIMEMultipart()
    msg["From"] = "your_email@example.com"
    msg["To"] = ", ".join(recipients)
    msg["Subject"] = subject
    
    msg.attach(MIMEText(content, "html"))
    
    with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
        server.login("your_email@example.com", "your_password")
        server.send_message(msg)
    
    print(f"邮件已发送至:{recipients}")

# 使用示例
report_content = """

每日数据报告

今日新增用户:150

活跃用户:1,200

""" send_email_report(["team@example.com"], "每日报告", report_content)

六、系统资源监控

使用 psutil 监控系统资源使用情况:

import psutil
import json

def monitor_system_resources():
    """监控系统 CPU、内存、磁盘使用情况"""
    metrics = {
        "cpu_percent": psutil.cpu_percent(interval=1),
        "memory_percent": psutil.virtual_memory().percent,
        "disk_percent": psutil.disk_usage("/").percent,
        "network_io": {
            "bytes_sent": psutil.net_io_counters().bytes_sent,
            "bytes_recv": psutil.net_io_counters().bytes_recv
        }
    }
    
    # 告警阈值
    if metrics["cpu_percent"] > 80:
        print("⚠️ CPU 使用率过高!")
    if metrics["memory_percent"] > 85:
        print("⚠️ 内存使用率过高!")
    
    return metrics

# 使用示例
resources = monitor_system_resources()
print(json.dumps(resources, indent=2))

七、API 数据自动采集

定时从 API 获取数据并存储:

import requests
import json
from datetime import datetime

def fetch_api_data(api_url, output_file):
    """从 API 获取数据并保存为 JSON"""
    try:
        response = requests.get(api_url, timeout=30)
        response.raise_for_status()
        
        data = {
            "timestamp": datetime.now().isoformat(),
            "data": response.json()
        }
        
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        print(f"数据已保存:{output_file}")
        
    except requests.exceptions.RequestException as e:
        print(f"API 请求失败:{e}")

# 使用示例
fetch_api_data("https://api.example.com/data", "data_backup.json")

八、图片批量处理

使用 Pillow 库批量处理图片:

from PIL import Image
from pathlib import Path

def batch_process_images(input_dir, output_dir, size=(800, 600)):
    """批量调整图片尺寸并压缩"""
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    
    for img_path in Path(input_dir).glob("*.jpg"):
        with Image.open(img_path) as img:
            img.thumbnail(size, Image.Resampling.LANCZOS)
            output_path = Path(output_dir) / img_path.name
            img.save(output_path, "JPEG", quality=85, optimize=True)
            print(f"处理完成:{img_path.name}")

# 使用示例
batch_process_images("./photos", "./processed_photos")

九、定时任务管理

使用 schedule 库创建定时任务:

import schedule
import time

def daily_task():
    """每日执行的任务"""
    print("执行每日任务...")
    # 添加你的任务逻辑

def hourly_task():
    """每小时执行的任务"""
    print("执行每小时任务...")

# 设置定时任务
schedule.every().day.at("09:00").do(daily_task)
schedule.every().hour.do(hourly_task)

# 运行调度器
while True:
    schedule.run_pending()
    time.sleep(60)

十、日志自动分析

分析日志文件并提取关键信息:

import re
from collections import Counter

def analyze_log_file(log_path):
    """分析日志文件,统计错误和警告"""
    error_pattern = re.compile(r"ERROR|CRITICAL", re.IGNORECASE)
    warning_pattern = re.compile(r"WARNING|WARN", re.IGNORECASE)
    
    errors = []
    warnings = []
    
    with open(log_path, "r", encoding="utf-8") as f:
        for line in f:
            if error_pattern.search(line):
                errors.append(line.strip())
            elif warning_pattern.search(line):
                warnings.append(line.strip())
    
    summary = {
        "total_errors": len(errors),
        "total_warnings": len(warnings),
        "recent_errors": errors[-5:] if errors else [],
        "recent_warnings": warnings[-5:] if warnings else []
    }
    
    return summary

# 使用示例
log_summary = analyze_log_file("/var/log/app.log")
print(f"错误数:{log_summary["total_errors"]}")
print(f"警告数:{log_summary["total_warnings"]}")

最佳实践建议

  1. 错误处理:始终使用 try-except 捕获异常,避免脚本意外终止
  2. 日志记录:使用 logging 模块记录关键操作,便于排查问题
  3. 配置分离:将配置项(如路径、API 密钥)放在单独的配置文件中
  4. 版本控制:使用 Git 管理脚本代码,追踪变更历史
  5. 定期测试:确保脚本在不同环境下都能正常运行

结语

自动化脚本的价值不仅在于节省时间,更在于减少人为错误、提高工作效率。从今天开始,选择一个重复性任务,用 Python 把它自动化吧!记住:最好的自动化脚本,是那个你今天就能开始写的脚本。

欢迎在评论区分享你的自动化脚本经验!

无关联文章

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:28 2 月, 2026

李炫炫

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2025 sudo-iのBlog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

鲁ICP备2024054662号

鲁公网安备37108102000450号