Python自动化办公:10个实用脚本提升效率
Python自动化办公:10个实用脚本提升效率
告别重复劳动,让Python帮你完成80%的办公自动化任务
你好,我是效率科技派。在上一篇文章中,我们探讨了Excel数据处理技巧。今天,我要分享更强大的工具——Python自动化办公。无论你是行政、财务、运营还是产品经理,掌握Python自动化都能让你的工作效率提升数倍。下面这10个实用脚本,你可以直接复制使用。## 1. 批量重命名文件
def batch_rename(folder_path, prefix="file_")::param folder_path: 文件夹路径files = os.listdir(folder_path)for i, filename in enumerate(files, 1):获取文件扩展名
ext = os.path.splitext(filename)[1]新文件名
new_name = f"{prefix}{i:03d}{ext}"重命名
os.path.join(folder_path, filename),os.path.join(folder_path, new_name)print(f"重命名: {filename} -> {new_name}")使用示例
batch_rename("/path/to/your/folder", "photo_")## 2. Excel数据合并
def merge_excel_files(folder_path, output_file="merged.xlsx"):for file in os.listdir(folder_path):if file.endswith(('.xlsx', '.xls')):file_path = os.path.join(folder_path, file)df = pd.read_excel(file_path)合并所有数据
merged_df = pd.concat(all_data, ignore_index=True)保存到新文件
merged_df.to_excel(output_file, index=False)print(f"合并完成!保存为: {output_file}")使用示例
merge_excel_files("./excel_files")## 3. 自动发送邮件
from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartdef send_email(subject, content, to_emails, from_email, password):创建邮件
msg['To'] = ', '.join(to_emails)添加正文
msg.attach(MIMEText(content, 'plain', 'utf-8'))发送邮件(以QQ邮箱为例)
server = smtplib.SMTP_SSL('smtp.qq.com', 465)server.login(from_email, password)使用示例(需要开启SMTP服务)
send_email(
subject="本周工作报告",
content="这是本周的工作总结...",
to_emails=["recipient@example.com"],
from_email="your_email@qq.com",
password="your_smtp_password"
)
## 4. PDF批量处理
from PyPDF2 import PdfMerger, PdfReader, PdfWriterdef merge_pdfs(pdf_files, output_file="merged.pdf"):merger.write(output_file)print(f"PDF合并完成: {output_file}")def extract_pages(input_pdf, pages, output_file="extracted.pdf")::param pages: 要提取的页码列表,如[1, 3, 5]reader = PdfReader(input_pdf)writer.add_page(reader.pages[page_num-1])with open(output_file, "wb") as output_pdf:print(f"页面提取完成: {output_file}")使用示例
merge_pdfs(["file1.pdf", "file2.pdf", "file3.pdf"])
extract_pages("report.pdf", [1, 3, 5])
## 5. 网页数据抓取
from bs4 import BeautifulSoupdef scrape_website(url, selector):发送请求
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()解析HTML
soup = BeautifulSoup(response.text, 'html.parser')根据选择器提取数据
elements = soup.select(selector)results = [elem.get_text(strip=True) for elem in elements]使用示例
titles = scrape_website("https://example.com", "h2.title")
print(titles)
## 6. 图片批量处理
def batch_resize_images(folder_path, size=(800, 600)):for filename in os.listdir(folder_path):if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):img_path = os.path.join(folder_path, filename)with Image.open(img_path) as img:调整大小
img_resized = img.resize(size, Image.Resampling.LANCZOS)保存(在原文件名前加"resized_")
new_filename = f"resized_{filename}"new_path = os.path.join(folder_path, new_filename)img_resized.save(new_path)print(f"处理完成: {filename}")print(f"处理失败 {filename}: {e}")使用示例
batch_resize_images("./photos", (1200, 800))
## 7. 数据备份脚本
from datetime import datetimedef backup_files(source_dir, backup_dir):创建备份目录(带时间戳)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")backup_path = os.path.join(backup_dir, f"backup_{timestamp}")复制整个文件夹
shutil.copytree(source_dir, backup_path)print(f"备份成功: {backup_path}")使用示例
backup_files("/important/documents", "/backup/location")
## 8. 定时任务执行
from datetime import datetimeprint(f"[{datetime.now()}] 正在生成每日报告...")这里可以调用其他函数,如发送邮件、处理数据等
print(f"[{datetime.now()}] 正在执行每周备份...")设置定时任务
schedule.every().day.at("09:00").do(daily_report)schedule.every().monday.at("18:00").do(weekly_backup)print("定时任务已启动,按Ctrl+C停止")运行调度器
每分钟检查一次
## 9. 数据清洗与转换
1. 删除空值
2. 去除字符串空格
str_cols = df_clean.select_dtypes(include=['object']).columnsdf_clean[col] = df_clean[col].str.strip()3. 标准化电话号码格式
if 'phone' in df_clean.columns:df_clean['phone'] = df_clean['phone'].apply(lambda x: re.sub(r'\D', '', str(x))4. 日期格式标准化
if 'date' in df_clean.columns:df_clean['date'] = pd.to_datetime(df_clean['date'], errors='coerce')使用示例
df = pd.read_csv("dirty_data.csv")
clean_df = clean_data(df)
clean_df.to_csv("clean_data.csv", index=False)
## 10. 自动化报告生成
import matplotlib.pyplot as pltfrom datetime import datetimedef generate_report(data_file, output_file="report.html"):读取数据
df = pd.read_csv(data_file)生成统计信息
"数据时间段": f"{df['date'].min()} 至 {df['date'].max()}","数值列统计": df.describe().to_html()创建图表
plt.figure(figsize=(10, 6))if 'value' in df.columns and 'date' in df.columns:df.plot(x='date', y='value', kind='line')生成HTML报告
数据分析报告 - {datetime.now().strftime('%Y-%m-%d')}body {{ font-family: Arial, sans-serif; margin: 40px; }}.stat {{ background:#f5f5f5; padding: 15px; margin: 10px 0; }}生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}{'' if 'chart_file' in locals() else ''}保存报告
with open(output_file, 'w', encoding='utf-8') as f:print(f"报告生成完成: {output_file}")使用示例
generate_report("sales_data.csv")
## 如何开始使用这些脚本?
### 第一步:安装Python环境
1. 访问 [python.org](https://www.python.org) 下载Python 3.8+2. 安装时勾选"Add Python to PATH"### 第二步:安装必要库
pip install pandas openpyxl PyPDF2 pillow requests beautifulsoup4 schedule matplotlib### 第三步:复制脚本使用
3. 运行:`python your_script.py`## 进阶学习建议
- **系统学习**:推荐《Python编程:从入门到实践》
- **社区交流**:加入Python学习群,交流经验
## 结语
Python自动化办公不是遥不可及的技术,而是可以立即应用的实用技能。从今天介绍的10个脚本开始,你会发现原来需要数小时的工作,现在几分钟就能完成。**记住**:最好的学习方式是实践。选一个最困扰你的重复性任务,用Python解决它!**下期预告**:明天我们将分享《办公软件快捷键大全》,让你掌握效率翻倍的秘密武器!**互动话题**:你工作中最想自动化的任务是什么?欢迎在评论区留言!
本文来自网友投稿或网络内容,如有侵犯您的权益请联系我们删除,联系邮箱:wyl860211@qq.com 。