Python 自动化办公的 10 个实用脚本

发布时间:2025-11-07 19:38

用Python编写简单自动化任务脚本 #生活乐趣# #日常生活趣事# #生活趣味分享# #科技小发明#

在现代职场中,自动化办公能够显著提高工作效率。Python 是一门强大的编程语言,通过简单易懂的语法和丰富的第三方库,可以帮助我们实现各种自动化任务。

在本文中,我们将介绍 10 个常见的 Python 自动化办公脚本,并结合生活中的实际例子进行说明,方便新手小白理解。

 

1. 批量重命名文件

在日常工作中,我们经常需要批量处理文件,例如将一组图片或文档重命名。使用 Python 的 os 模块可以轻松实现。

假设你有一堆图片文件,需要将它们统一命名为“项目_1.jpg”, “项目_2.jpg”等等。

import os

# 指定文件夹路径
folder_path = 'path/to/your/folder'

# 切换到指定目录 os.chdir(folder_path) # 遍历文件夹中的所有文件 for count, filename in enumerate(os.listdir(folder_path)):     # 生成新的文件名     new_name = f"项目_{count + 1}.jpg"          # 重命名文件     os.rename(filename, new_name) print("文件重命名完成!")

 

2. 自动发送电子邮件

通过 Python 的 smtplib 库,我们可以轻松地发送电子邮件,这对于发送报告、通知等信息非常有用。

假设你需要每天向你的团队发送一封日报,包含过去一天的工作总结。

import smtplib from email.mime.text import MIMEText # 邮件内容 subject = "每日工作总结" body = "今天完成了以下工作:\n- 完成了项目 A\n- 开始了项目 B" # 发件人和收件人 sender = "your_email@example.com" receiver = "team_member@example.com" # 创建邮件 msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver # 发送邮件 with smtplib.SMTP('smtp.example.com', 587) as server:     server.starttls()     server.login(sender, 'your_password')     server.send_message(msg) print("邮件发送成功!")

 

3. 从 Excel 中提取数据

使用 pandas 库,我们可以快速处理 Excel 文件,例如提取特定的数据或进行数据分析。

假设你有一个 Excel 表格,其中包含销售数据,你想提取出所有超过 1000 元的销售记录。

import pandas as pd # 读取 Excel 文件 df = pd.read_excel('sales_data.xlsx') # 提取销售额超过 1000 的记录 high_sales = df[df['Sales'] > 1000] # 打印结果 print("销售额超过 1000 的记录:\n", high_sales)

 

4. 自动化生成 PDF 报告

借助 reportlab 库,我们可以动态生成 PDF 文件,用于创建报告、发票等文档。

假设你需要为每个项目生成一份 PDF 报告,包括项目名称、负责人和状态。

from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas # 创建 PDF 文件 def generate_pdf(project_name, owner, status):     c = canvas.Canvas(f"{project_name}_report.pdf", pagesize=letter)     c.drawString(100, 750, f"项目名称: {project_name}")     c.drawString(100, 730, f"负责人: {owner}")     c.drawString(100, 710, f"状态: {status}")     c.save() # 生成示例报告 generate_pdf("项目A", "张三", "进行中") print("PDF 报告生成成功!")

 

5. 网络爬虫获取网页数据

使用 requests 和 BeautifulSoup 库,我们可以从网页上抓取数据,例如提取新闻标题、产品价格等信息。

假设你想从某个新闻网站提取最新的新闻标题。

import requests from bs4 import BeautifulSoup # 请求网页 url = 'https://news.ycombinator.com/' response = requests.get(url) # 解析网页 soup = BeautifulSoup(response.text, 'html.parser') # 提取新闻标题 titles = [title.get_text() for title in soup.find_all('a', class_='storylink')] # 打印所有标题 for index, title in enumerate(titles):     print(f"{index + 1}: {title}")

 

6. 定时执行任务

使用 schedule 库可以设置定时任务,例如每天定时发送邮件或运行数据分析脚本。

假设你希望每天晚上 7 点自动发送一封周报邮件。

import schedule import time def job():     print("发送周报邮件...") # 每天 19:00 执行任务 schedule.every().day.at("19:00").do(job) while True:     schedule.run_pending()     time.sleep(60)  # 等待 1 分钟

 

7. 批量下载文件

通过 Python 可以自动化下载多个文件,例如从一个网页或云端服务下载数据集。

假设你需要从某个网站批量下载图片。

import requests # 图片链接列表 image_urls = [     'http://example.com/image1.jpg',     'http://example.com/image2.jpg',     'http://example.com/image3.jpg' ] # 批量下载 for url in image_urls:     response = requests.get(url)     with open(url.split('/')[-1], 'wb') as f:         f.write(response.content) print("所有图片下载完成!")

 

8. 自动整理文件

利用 os 和 shutil 模块,可以根据文件类型将文件自动分类整理到不同的文件夹中。

假设你的下载文件夹里混杂着很多文件,你希望按照文件类型进行整理,比如将图片、文档和视频分别放到不同的文件夹。

import os import shutil # 指定下载文件夹路径 downloads_folder = '/path/to/downloads' # 创建文件类型对应的文件夹 os.makedirs(os.path.join(downloads_folder, 'Images'), exist_ok=True) os.makedirs(os.path.join(downloads_folder, 'Documents'), exist_ok=True) os.makedirs(os.path.join(downloads_folder, 'Videos'), exist_ok=True) # 遍历下载文件夹中的所有文件 for filename in os.listdir(downloads_folder):     if filename.endswith('.jpg') or filename.endswith('.png'):         shutil.move(os.path.join(downloads_folder, filename), os.path.join(downloads_folder, 'Images', filename))     elif filename.endswith('.pdf') or filename.endswith('.docx'):         shutil.move(os.path.join(downloads_folder, filename), os.path.join(downloads_folder, 'Documents', filename))     elif filename.endswith('.mp4'):         shutil.move(os.path.join(downloads_folder, filename), os.path.join(downloads_folder, 'Videos', filename)) print("文件整理完成!")

 

9. 数据可视化

使用 matplotlib 库,可以创建各种图表,对数据进行可视化分析,这样更直观。

假设你想要可视化每月的销售数据,以便了解趋势。

import matplotlib.pyplot as plt # 定义销售数据 months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'] sales = [2000, 3000, 4000, 5000, 6000] # 创建柱状图 plt.bar(months, sales, color='skyblue') plt.title('每月销售数据') plt.xlabel('月份') plt.ylabel('销售额') plt.show()

 

10. 从 Google Sheets 获取数据

通过 gspread 库,可以轻松访问 Google Sheets 中的数据,便于各类办公自动化任务。

如果你在 Google Sheets 上维护了一份客户名单,想要获取这些数据进行处理。

import gspread from oauth2client.service_account import ServiceAccountCredentials # 使用 OAuth2 认证 scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name('path/to/credentials.json', scope) client = gspread.authorize(creds) # 打开 Google Sheets 文件 sheet = client.open("客户名单").sheet1 # 获取所有数据 data = sheet.get_all_records() # 打印客户名单 for record in data:     print(record)

 

总结

通过以上 10 个 Python 自动化办公脚本示例,我们可以看到 Python 在提高工作效率方面的巨大潜力。这些脚本适合新手小白学习,并能帮助他们解决实际工作中遇到的问题。

如果你希望深入了解某个脚本的实现细节或有其他问题,请随时联系我!希望这些示例能够激励你在自动化办公的旅程中不断探索和实践!

网址:Python 自动化办公的 10 个实用脚本 https://www.yuejiaxmz.com/news/view/1402327

相关内容

10个Python脚本,轻松实现日常任务自动化!
10个常用Python自动化脚本
5个实用的自动化Python脚本
五个方便好用的Python自动化脚本
10个Python脚本自动化日常任务
10 个 Python 脚本来自动化你的日常任务
【源码】10 个用于日常自动化的 Python 脚本!
10个 Python 脚本来自动化你的日常任务
【Python学习】10个Python脚本轻松实现日常任务自动化!
10个Python脚本轻松实现日常任务自动化

随便看看