前言

分享几个实用的 Python 自动化办公脚本。这些脚本可以帮助你简化日常工作,提高效率。无论是处理 Excel 文件、发送邮件,还是自动化网页操作,Python 都能派上用场。持续更新

批量重命名文件

如果你需要对一堆文件进行重命名,比如给文件添加前缀或后缀,可以使用以下脚本:

import os

def batch_rename_files(directory, prefix):
    """批量重命名指定目录下的所有文件,添加前缀"""
    for filename in os.listdir(directory):
        new_name = f"{prefix}_{filename}"
        os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
    print("文件重命名完成")

# 使用示例
batch_rename_files('path/to/your/directory', 'new_prefix')

自动发送电子邮件

使用 smtplib 库,你可以轻松实现自动发送电子邮件的功能。

import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email):
    """发送电子邮件"""
    from_email = 'your_email@example.com'
    password = 'your_email_password'

    # 创建邮件内容
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    # 发送邮件
    with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
        server.login(from_email, password)
        server.send_message(msg)
        print("邮件发送成功")

# 使用示例
send_email("测试主题", "这是一封测试邮件", "recipient@example.com")

批量处理 Excel 文件

import pandas as pd

def process_excel(file_path):
    """读取 Excel 文件并处理数据"""
    df = pd.read_excel(file_path)  # 读取 Excel 文件
    df['新列'] = df['原列'] * 2  # 在 DataFrame 中添加新列
    df.to_excel('processed_file.xlsx', index=False)  # 保存处理后的结果
    print("Excel 文件处理完成")

# 使用示例
process_excel('path/to/your/excel_file.xlsx')

网页抓取数据

使用 requests 和 BeautifulSoup,可以轻松从网页抓取数据。

import requests
from bs4 import BeautifulSoup

def fetch_data(url):
    """从指定 URL 抓取数据"""
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    titles = [title.get_text() for title in soup.find_all('h2')]  # 假设标题在 <h2> 标签中
    print("抓取到的标题:")
    for title in titles:
        print(title)

# 使用示例
fetch_data('https://example.com')

文件备份

这个脚本可以帮助你快速备份指定目录中的文件。

import shutil
import os
import datetime

def backup_files(source_directory, backup_directory):
    """备份文件到指定目录"""
    date_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_path = os.path.join(backup_directory, f"backup_{date_str}")
    shutil.copytree(source_directory, backup_path)  # 复制整个目录
    print(f"备份完成: {backup_path}")

# 使用示例
backup_files('path/to/source_directory', 'path/to/backup_directory')

自动生成报告

如果你需要根据数据生成报告,可以使用 pandas 来处理数据并生成 PDF 或 Excel 格式的报告。

import pandas as pd

def generate_report(data):
    """根据数据生成简单的 Excel 报告"""
    df = pd.DataFrame(data)
    df.to_excel('report.xlsx', index=False)
    print("报告已生成: report.xlsx")

# 使用示例
data = {
    '姓名': ['张三', '李四'],
    '分数': [90, 85]
}
generate_report(data)

图片批量处理

使用 Pillow 库,可以批量处理图片,例如调整大小或格式转换。

from PIL import Image
import os

def resize_images(source_directory, output_directory, size=(800, 800)):
    """调整指定目录下所有图片的大小"""
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for filename in os.listdir(source_directory):
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(source_directory, filename)
            img = Image.open(img_path)
            img = img.resize(size)
            img.save(os.path.join(output_directory, filename))
            print(f"已调整大小并保存: {filename}")

# 使用示例
resize_images('path/to/source_images', 'path/to/output_images', (800, 800))

数据库操作

import sqlite3

def create_table():
    """创建一个简单的SQLite表"""
    conn = sqlite3.connect('example.db')
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
    conn.commit()
    conn.close()
    print("表创建成功")

# 使用示例
create_table()

自动化日程提醒

可以使用 schedule 库设置定时任务,比如每天发送提醒邮件。

import schedule
import time

def job():
    print("这是您的日程提醒!请记得查看日程安排。")

# 设置每天的提醒时间
schedule.every().day.at("10:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

网络监控

import requests

def check_website(url):
    """检查网站是否正常"""
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"{url} 正常运行")
        else:
            print(f"{url} 返回状态码: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"访问 {url} 时发生错误: {e}")

# 使用示例
check_website('https://example.com')

标签: none