专业编程基础技术教程

网站首页 > 基础教程 正文

如何用python解决日常自动化工作任务

ccvgpt 2025-03-20 12:47:02 基础教程 10 ℃

Python 是自动化任务的绝佳工具,能够高效处理重复性工作。以下从多个场景出发,为你提供实用解决方案和代码示例:

一、办公文档自动化

场景案例:每月合并20个部门的Excel报表

如何用python解决日常自动化工作任务

import pandas as pd
import os

def merge_excel(folder_path):
    all_data = []
    for file in os.listdir(folder_path):
        if file.endswith('.xlsx'):
            df = pd.read_excel(os.path.join(folder_path, file))
            all_data.append(df)
    combined = pd.concat(all_data)
    combined.to_excel('merged_report.xlsx', index=False)

# 使用示例
merge_excel('/path/to/reports_folder')

二、邮件自动化

场景案例:每日定时发送数据报告

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

def send_email(subject, content, attachment_path=None):
    sender = 'your_email@example.com'
    receiver = 'target@example.com'
    password = 'your_app_password'  # 建议使用应用专用密码
    
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    
    # 正文内容
    msg.attach(MIMEText(content, 'plain'))
    
    # 添加附件
    if attachment_path:
        with open(attachment_path, 'rb') as f:
            part = MIMEApplication(f.read())
            part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_path))
            msg.attach(part)
    
    # 发送邮件
    with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, msg.as_string())

# 使用示例
send_email('Daily Report', 'Please check the attached report.', 'daily_report.xlsx')

三、文件管理系统

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

import shutil
import os
from pathlib import Path

DOWNLOAD_PATH = Path.home() / 'Downloads'

def organize_downloads():
    # 创建分类目录
    categories = {
        'Documents': ['.pdf', '.docx', '.xlsx'],
        'Images': ['.jpg', '.png', '.gif'],
        'Archives': ['.zip', '.rar']
    }
    
    for category in categories:
        (DOWNLOAD_PATH / category).mkdir(exist_ok=True)
    
    # 遍历文件并移动
    for file in DOWNLOAD_PATH.iterdir():
        if file.is_file():
            suffix = file.suffix.lower()
            for category, extensions in categories.items():
                if suffix in extensions:
                    dest = DOWNLOAD_PATH / category / file.name
                    if not dest.exists():
                        shutil.move(str(file), str(dest))
                    break

organize_downloads()

四、浏览器自动化

场景案例:自动填写Web表单

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://example.com/form')

try:
    # 等待页面加载
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "username"))
    )
    
    # 填写表单
    driver.find_element(By.ID, 'username').send_keys('test_user')
    driver.find_element(By.ID, 'password').send_keys('secure_pass123')
    driver.find_element(By.XPATH, '//button[@type="submit"]').click()
    
finally:
    driver.quit()

五、GUI自动化

场景案例:批量重命名图片

import pyautogui
import time

def batch_rename_images(folder_path):
    pyautogui.hotkey('win', 'e')  # 打开文件资源管理器
    time.sleep(2)
    
    pyautogui.write(folder_path)
    pyautogui.press('enter')
    time.sleep(1)
    
    # 全选文件
    pyautogui.hotkey('ctrl', 'a')
    time.sleep(0.5)
    
    # 触发重命名
    pyautogui.press('f2')
    pyautogui.write('vacation_')
    pyautogui.press('enter')

# 使用前请确认文件资源管理器的位置
# batch_rename_images(r'C:\Users\YourName\Pictures\Summer2023')

六、定时任务管理

场景案例:每天自动备份数据库

import schedule
import time
import subprocess

def backup_database():
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    cmd = f'mysqldump -u root -pPASSWORD database > backup_{timestamp}.sql'
    subprocess.run(cmd, shell=True)

# 设置每天凌晨3点执行
schedule.every().day.at("03:00").do(backup_database)

while True:
    schedule.run_pending()
    time.sleep(60)  # 每分钟检查一次

进阶技巧:

  1. 错误处理:使用try-except块和日志记录
import logging
logging.basicConfig(filename='automation.log', level=logging.ERROR)

try:
    # 你的自动化代码
except Exception as e:
    logging.error(f"Error occurred: {str(e)}", exc_info=True)
  1. 多线程处理:加速批量任务
from concurrent.futures import ThreadPoolExecutor

def process_file(file_path):
    # 文件处理逻辑

with ThreadPoolExecutor(max_workers=4) as executor:
    results = executor.map(process_file, file_list)
  1. 配置文件管理:使用configparser
import configparser

config = configparser.ConfigParser()
config.read('config.ini')

smtp_server = config['EMAIL']['SMTP_SERVER']
username = config['EMAIL']['USERNAME']

常用工具库推荐:

  • 文本处理:re (正则表达式)
  • 网络请求:requests
  • 图像处理:Pillow
  • PDF处理:PyPDF2
  • 系统交互:subprocess
  • 任务调度:schedule
  • 桌面通知:plyer

建议从简单任务开始实践,逐步组合不同功能模块。遇到问题时:

  1. 查阅官方文档
  2. 使用print()调试输出
  3. 在Stack Overflow搜索错误信息
  4. 使用Python调试器pdb

通过持续实践,你可以逐步构建起适合自己工作流程的自动化体系,将重复性工作交给Python处理,专注更有价值的工作内容。

Tags:

最近发表
标签列表