显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 ====== 第四十章:自动化脚本 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 自动化文件操作 * 自动化系统任务 * 处理Excel和PDF * 发送邮件通知 ===== 文件自动化 ===== <code python> import os import shutil from pathlib import Path # 批量重命名 for i, file in enumerate(os.listdir('.')): if file.endswith('.txt'): os.rename(file, f'doc_{i:03d}.txt') # 按扩展名整理文件 for file in Path('.').iterdir(): if file.is_file(): ext = file.suffix[1:] or 'no_ext' os.makedirs(ext, exist_ok=True) shutil.move(str(file), f"{ext}/{file.name}") </code> ===== 处理Excel ===== <code python> import openpyxl # 读取 wb = openpyxl.load_workbook('data.xlsx') sheet = wb.active print(sheet['A1'].value) # 写入 wb = openpyxl.Workbook() sheet = wb.active sheet['A1'] = 'Hello' sheet.append(['Data1', 'Data2']) wb.save('output.xlsx') </code> ===== 发送邮件 ===== <code python> import smtplib from email.mime.text import MIMEText def send_email(subject, body, to_email): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = 'sender@example.com' msg['To'] = to_email with smtplib.SMTP('smtp.example.com', 587) as server: server.starttls() server.login('user', 'password') server.send_message(msg) </code> ===== 本章实战 ===== 1. 自动备份脚本 2. 数据报表生成 3. 定时任务调度 下一章:[[python_course:chapter41|第四十一章:测试与调试]] 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 python/chapter40.txt 最后更改: 2026/04/09 14:43由 张叶安 登录