百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

2025年必学的Python自动化办公的15个实用脚本

itomcoil 2025-05-15 18:24 18 浏览

2025年必学的Python自动化办公的6个实用脚本及其代码示例。这些脚本涵盖了文件备份、邮件通知、网页抓取、报告生成、数据处理和团队协作等多个场景,帮助用户高效完成日常办公任务。

1. 自动备份文件

自动备份文件是确保数据安全的重要任务。以下脚本使用shutil库将指定文件夹中的文件备份到目标目录,并添加时间戳以区分不同版本的备份。

import shutil

import os

from datetime import datetime

def backup_files(source_dir, backup_dir):

# 创建备份目录(如果不存在)

if not os.path.exists(backup_dir):

os.makedirs(backup_dir)

# 获取当前时间戳

timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

# 遍历源目录并复制文件

for filename in os.listdir(source_dir):

source_file = os.path.join(source_dir, filename)

if os.path.isfile(source_file):

backup_file = os.path.join(backup_dir, f"{timestamp}_{filename}")

shutil.copy2(source_file, backup_file)

print(f"Backed up: {filename} to {backup_file}")

# 示例调用

source_directory = "/path/to/source"

backup_directory = "/path/to/backup"

backup_files(source_directory, backup_directory)

2. 发送电子邮件通知

通过smtplib和email库,可以编写脚本自动发送电子邮件通知。以下脚本演示如何发送带有附件的邮件。

python

复制

import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersdef send_email(sender, receiver, subject, body, attachment_path=None):
# 设置邮件内容
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))

# 添加附件
if attachment_path:
with open(attachment_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={attachment_path}')
msg.attach(part)

# 发送邮件
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(sender, "your_password")
server.send_message(msg)
print("Email sent successfully!")# 示例调用sender_email = "your_email@example.com"receiver_email = "receiver@example.com"subject = "Automated Email Notification"body = "This is an automated email sent using Python."attachment_path = "/path/to/attachment.txt"send_email(sender_email, receiver_email, subject, body, attachment_path)

3. 自动下载网页内容

使用requests和BeautifulSoup库,可以编写脚本自动下载网页内容并保存到本地文件。

python

复制

import requestsfrom bs4 import BeautifulSoupdef download_webpage(url, output_file):
# 发送HTTP请求
response = requests.get(url)
if response.status_code == 200:
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 保存网页内容到文件
with open(output_file, 'w', encoding='utf-8') as file:
file.write(soup.prettify())
print(f"Webpage saved to {output_file}")
else:
print(f"Failed to download webpage. Status code: {response.status_code}")# 示例调用url = "https://www.example.com"output_file = "webpage.html"download_webpage(url, output_file)

4. 生成PDF报告

使用ReportLab库,可以自动化生成PDF格式的报告。以下脚本生成一个简单的PDF报告。

python

复制

from reportlab.lib.pagesizes import letterfrom reportlab.pdfgen import canvasdef generate_pdf_report(output_file, title, content):
# 创建PDF文件
c = canvas.Canvas(output_file, pagesize=letter)
c.setFont("Helvetica", 12)

# 添加标题
c.drawString(100, 750, title)

# 添加内容
y_position = 700
for line in content:
c.drawString(100, y_position, line)
y_position -= 20

# 保存PDF
c.save()
print(f"PDF report generated: {output_file}")# 示例调用output_file = "report.pdf"title = "Monthly Report"content = ["Section 1: Introduction", "Section 2: Data Analysis", "Section 3: Conclusion"]generate_pdf_report(output_file, title, content)

5. 自动整理Excel数据

使用Pandas库,可以自动化整理Excel数据。以下脚本读取多个Excel文件并合并数据。

python

复制

import pandas as pdimport osdef merge_excel_files(directory, output_file):
# 获取目录中的所有Excel文件
excel_files = [f for f in os.listdir(directory) if f.endswith('.xlsx')]

# 合并数据
combined_data = pd.DataFrame()
for file in excel_files:
file_path = os.path.join(directory, file)
data = pd.read_excel(file_path)
combined_data = pd.concat([combined_data, data], ignore_index=True)

# 保存合并后的数据
combined_data.to_excel(output_file, index=False)
print(f"Data merged and saved to {output_file}")# 示例调用directory = "/path/to/excel_files"output_file = "combined_data.xlsx"merge_excel_files(directory, output_file)

6. 自动发送Slack消息

使用slack_sdk库,可以编写脚本自动发送消息到Slack频道。

python

复制

from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrordef send_slack_message(token, channel, message):
# 初始化Slack客户端
client = WebClient(token=token)

try:
# 发送消息
response = client.chat_postMessage(channel=channel, text=message)
print("Message sent successfully!")
except SlackApiError as e:
print(f"Error sending message: {e.response['error']}")# 示例调用slack_token = "xoxb-your-slack-token"channel_name = "#general"message_text = "This is an automated message sent from Python!"send_slack_message(slack_token, channel_name, message_text)

总结

以上6个脚本展示了Python在自动化办公中的强大能力。通过掌握这些脚本,用户可以显著提高工作效率,减少重复性任务的时间消耗。随着Python生态系统的不断发展,其在自动化办公领域的应用将更加广泛和深入。

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...