page contents

Python教程-Python 自动化办公的 10 大脚本!

今天我们将讨论 10 个实用的 Python 自动化办公脚本。这些脚本可以帮助你简化日常工作,提高效率。无论是处理 Excel 文件、发送邮件,还是自动化网页操作,Python 都能派上用场。

attachments-2024-11-ekoGRf1C674524fe8c309.png今天我们将讨论 10 个实用的 Python 自动化办公脚本。这些脚本可以帮助你简化日常工作,提高效率。无论是处理 Excel 文件、发送邮件,还是自动化网页操作,Python 都能派上用场。

1. 批量重命名文件

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

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')说明:此脚本遍历指定目录中的所有文件,并为每个文件添加指定的前缀。

2. 自动发送电子邮件

使用 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")说明:确保替换邮件地址和 SMTP 服务器信息,以使其适应你的邮箱设置。

3. 批量处理 Excel 文件

使用 pandas 和 openpyxl 库,可以轻松读取和写入 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')说明:此脚本读取指定的 Excel 文件,对其中一列的数据进行简单的数学运算,然后保存处理后的结果到新的 Excel 文件中。

4. 网页抓取数据

使用 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')

说明:该脚本访问指定的 URL,解析 HTML 内容,并提取所有 <h2> 标签内的文本。

5. 文件备份

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

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')说明:该脚本使用 shutil.copytree() 方法复制源目录中的所有文件到备份目录。

6. 自动生成报告

如果你需要根据数据生成报告,可以使用 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)说明:该脚本将样本数据转换为一个 Excel 文件。

7. 图片批量处理

使用 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))说明:该脚本遍历指定目录,调整每张图片的大小并保存到输出目录。

8. 数据库操作

使用 sqlite3 库,可以方便地与 SQLite 数据库进行交互。

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()说明:此脚本连接到 SQLite 数据库并创建一个用户表。

9. 自动化日程提醒

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

import schedule

import time

def job():

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

# 设置每天的提醒时间

schedule.every().day.at("10:00").do(job)

while True:

    schedule.run_pending()

    time.sleep(1)说明:该脚本每天下午 10 点执行预定的提醒任务。

10. 网络监控

可以编写一个简单的脚本来监控特定网站的状态,确保它们正常运行。

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')说明:该脚本尝试访问指定的网站,并根据响应状态码判断网站是否正常运行。

总结

以上就是 Python 自动化办公的 10 大脚本。这些脚本可以帮助你简化日常工作,提高生产力。掌握这些基本技能后,你将能够更高效地处理各种办公任务。

更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2024-11-26 09:32
  • 阅读 ( 134 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
小柒
小柒

1734 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1734 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章