当前位置: 首页 > news >正文

用 Python 写一个自动化办公小助手

在日常办公中,我们常常会遇到一些重复性的任务,如批量处理文件、发送邮件、生成报表等。这些任务不仅耗时,还容易出错。今天,就让我们一起用 Python 编写一个自动化办公小助手,帮助你高效完成这些任务。

一、自动化办公小助手的功能

(一)批量重命名文件

import osdef 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')

(二)发送邮件

import smtplib
from email.mime.text import MIMETextdef send_email(to_email, subject, body):"""发送邮件"""sender = "your_email@example.com"password = "your_password"msg = MIMEText(body)msg['Subject'] = subjectmsg['From'] = sendermsg['To'] = to_emailwith smtplib.SMTP('smtp.example.com', 587) as server:server.starttls()server.login(sender, password)server.sendmail(sender, to_email, msg.as_string())print("邮件发送成功")# 示例:发送邮件
send_email('recipient@example.com', 'Subject', 'Email body')

(三)生成 Excel 报表

import pandas as pddef generate_excel_report(data, output_file):"""生成 Excel 报表"""df = pd.DataFrame(data)df.to_excel(output_file, index=False)print("报表生成完成")# 示例:生成 Excel 报表
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
generate_excel_report(data, 'report.xlsx')

(四)批量处理 Excel 文件

import pandas as pd
import osdef batch_process_excel_files(directory, output_file):"""批量处理 Excel 文件,合并到一个文件中"""all_data = []for filename in os.listdir(directory):if filename.endswith('.xlsx'):file_path = os.path.join(directory, filename)df = pd.read_excel(file_path)all_data.append(df)combined_df = pd.concat(all_data, ignore_index=True)combined_df.to_excel(output_file, index=False)print("文件处理完成")# 示例:批量处理 Excel 文件
batch_process_excel_files('path/to/your/directory', 'combined_output.xlsx')

(五)定时任务

from apscheduler.schedulers.blocking import BlockingScheduler
import datetimedef my_job():print("任务执行时间:", datetime.datetime.now())# 示例:设置定时任务
scheduler = BlockingScheduler()
scheduler.add_job(my_job, 'interval', seconds=10)
scheduler.start()

二、整合自动化办公小助手

将上述功能整合到一个脚本中,创建一个自动化办公小助手。

import os
import smtplib
from email.mime.text import MIMEText
import pandas as pd
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime# 批量重命名文件
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("文件重命名完成")# 发送邮件
def send_email(to_email, subject, body):sender = "your_email@example.com"password = "your_password"msg = MIMEText(body)msg['Subject'] = subjectmsg['From'] = sendermsg['To'] = to_emailwith smtplib.SMTP('smtp.example.com', 587) as server:server.starttls()server.login(sender, password)server.sendmail(sender, to_email, msg.as_string())print("邮件发送成功")# 生成 Excel 报表
def generate_excel_report(data, output_file):df = pd.DataFrame(data)df.to_excel(output_file, index=False)print("报表生成完成")# 批量处理 Excel 文件
def batch_process_excel_files(directory, output_file):all_data = []for filename in os.listdir(directory):if filename.endswith('.xlsx'):file_path = os.path.join(directory, filename)df = pd.read_excel(file_path)all_data.append(df)combined_df = pd.concat(all_data, ignore_index=True)combined_df.to_excel(output_file, index=False)print("文件处理完成")# 定时任务
def my_job():print("任务执行时间:", datetime.datetime.now())# 主函数
def main():# 批量重命名文件batch_rename_files('path/to/your/directory', 'new_prefix')# 发送邮件send_email('recipient@example.com', 'Subject', 'Email body')# 生成 Excel 报表data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}generate_excel_report(data, 'report.xlsx')# 批量处理 Excel 文件batch_process_excel_files('path/to/your/directory', 'combined_output.xlsx')# 设置定时任务scheduler = BlockingScheduler()scheduler.add_job(my_job, 'interval', seconds=10)scheduler.start()if __name__ == "__main__":main()

三、总结

通过本文的介绍,你已经学会了如何使用 Python 编写一个自动化办公小助手,包括批量重命名文件、发送邮件、生成 Excel 报表、批量处理 Excel 文件和设置定时任务。希望这些功能能帮助你高效完成日常办公任务。

http://www.dtcms.com/a/503271.html

相关文章:

  • 《二叉树“防塌”指南:AVL 树如何用旋转 “稳住” 平衡?》
  • 网站制作wap页面wordpress微信公众平台开发
  • 分解如何利用c++修复小程序的BUG
  • 若依微服务 nacos的配置文件
  • 63.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--预算告警
  • 网站建设没有业务怎么办德州网架公司
  • 九成自动化备份知乎专栏
  • 圆形平面阵列与平面方形阵的导向矢量:原理与实现
  • Altium Designer(AD24)Help帮助功能总结
  • 网站建设 个人2012版本wordpress
  • 6.2 域名系统 (答案见原书 P271)
  • php怎么网站开发上海网站建设86215
  • C程序中的指针:动态内存、链表与函数指针
  • 免费注册网站软件2022推广app赚佣金平台
  • 【Linux运维实战】彻底修复 CVE-2011-5094 漏洞
  • Java | 基于redis实现分布式批量设置各个数据中心的服务器配置方案设计和代码实践
  • STM32中硬件I2C的时钟占空比
  • iFlutter --> Flutter 开发者 的 IntelliJ IDEA / Android Studio 插件
  • Easyx图形库应用(和lua结合使用)
  • 网站建设计划表模板网络运营需要学什么专业
  • Scrapy 框架入门:高效搭建爬虫项目
  • 【JVM】详解 垃圾回收
  • 【前端魔法】实现网站一键切换主题
  • 电子 东莞网站建设wordpress 图片服务器配置
  • Spring Boot 3零基础教程,WEB 开发 通过配置类代码方式修改静态资源配置 笔记31
  • Vue模块与组件、模块化与组件化
  • SiriKali,一款跨平台的加密文件管理器
  • 构建优雅的 Spring Boot Starter:深入掌握国际化与配置覆盖的最佳实践
  • 网站建设的意义单页式网站
  • 易申建设网站兼职做ps网站