10个Python自动化脚本帮你每天省下2小时工作时间作为开发者我们每天都会遇到很多重复机械的工作批量处理文件、整理数据、发邮件、下载资源等等。这些工作消耗了大量时间其实都可以用Python脚本自动化搞定。今天分享10个我日常高频使用的Python脚本亲测能帮你每天省下至少2小时的摸鱼时间。—## 1. 批量文件重命名脚本场景需要批量修改某个文件夹下的文件名比如统一加前缀、替换特定字符、修改后缀名。pythonimport osdef batch_rename(folder_path, prefix, replace_old, replace_new, suffixNone): for filename in os.listdir(folder_path): old_path os.path.join(folder_path, filename) if os.path.isfile(old_path): # 处理文件名 name, ext os.path.splitext(filename) new_name prefix name.replace(replace_old, replace_new) new_name suffix if suffix else ext new_path os.path.join(folder_path, new_name) os.rename(old_path, new_path) print(f重命名成功{filename} → {new_name})# 使用示例batch_rename( folder_path./test_files, prefix2026_, replace_old旧版, replace_new新版)使用说明替换folder_path为你的文件夹路径按需设置前缀、替换规则和后缀即可。—## 2. 批量Excel数据合并脚本场景几十个结构相同的Excel表需要合并成一个总表手动复制粘贴太麻烦。pythonimport pandas as pdimport osdef merge_excels(folder_path, output_file合并结果.xlsx): df_list [] for filename in os.listdir(folder_path): if filename.endswith((.xlsx, .xls)) and not filename.startswith(~$): file_path os.path.join(folder_path, filename) df pd.read_excel(file_path) df_list.append(df) print(f已读取文件{filename}) total_df pd.concat(df_list, ignore_indexTrue) total_df.to_excel(output_file, indexFalse) print(f合并完成共{len(total_df)}条数据已保存到{output_file})# 使用示例merge_excels(folder_path./excel_files)使用说明安装依赖pip install pandas openpyxl替换文件夹路径即可自动合并所有Excel文件。—## 3. 自动发送邮件脚本场景需要给多人发送格式类似的邮件比如通知、报表、祝福邮件手动发太费时间。pythonimport smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartdef send_email(smtp_server, smtp_port, sender_email, sender_password, receiver_emails, subject, content, attachmentsNone): msg MIMEMultipart() msg[From] sender_email msg[To] , .join(receiver_emails) msg[Subject] subject # 添加正文 msg.attach(MIMEText(content, plain, utf-8)) # 添加附件 if attachments: for file_path in attachments: with open(file_path, rb) as f: part MIMEText(f.read(), base64, utf-8) part[Content-Disposition] fattachment; filename{os.path.basename(file_path)} msg.attach(part) # 发送邮件 with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_emails, msg.as_string()) print(邮件发送成功)# 使用示例QQ邮箱send_email( smtp_serversmtp.qq.com, smtp_port465, sender_email你的QQ邮箱qq.com, sender_password你的授权码, receiver_emails[收件人1xxx.com, 收件人2xxx.com], subject月度报表通知, content您好附件是本月的报表请查收。, attachments[./月度报表.xlsx])使用说明不同邮箱的SMTP服务器和授权码获取方式不同QQ邮箱在设置-账号里开通SMTP服务获取授权码。—## 4. 网页内容批量抓取脚本场景需要批量抓取某个网站的公开内容比如新闻、产品信息、数据列表等。pythonimport requestsfrom bs4 import BeautifulSoupimport csvdef crawl_website(url, output_file抓取结果.csv): headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 } response requests.get(url, headersheaders) soup BeautifulSoup(response.text, html.parser) # 这里以抓取博客文章列表为例根据实际网站修改选择器 articles soup.select(.article-item) result [] for article in articles: title article.select_one(.title).text.strip() author article.select_one(.author).text.strip() date article.select_one(.date).text.strip() result.append({标题: title, 作者: author, 发布日期: date}) # 保存到CSV with open(output_file, w, newline, encodingutf-8-sig) as f: writer csv.DictWriter(f, fieldnamesresult[0].keys()) writer.writeheader() writer.writerows(result) print(f抓取完成共{len(result)}条数据已保存到{output_file})# 使用示例crawl_website(urlhttps://blog.csdn.net/)使用说明安装依赖pip install requests beautifulsoup4根据目标网站的HTML结构修改选择器即可。—## 5. 图片批量压缩脚本场景大量图片需要压缩大小上传到网站或者发给客户的时候用不用逐个打开PS修改。pythonfrom PIL import Imageimport osdef compress_images(folder_path, quality80, max_widthNone, output_folder./compressed): os.makedirs(output_folder, exist_okTrue) for filename in os.listdir(folder_path): if filename.lower().endswith((.jpg, .jpeg, .png)): file_path os.path.join(folder_path, filename) with Image.open(file_path) as img: # 等比例缩放 if max_width and img.width max_width: ratio max_width / img.width new_height int(img.height * ratio) img img.resize((max_width, new_height), Image.Resampling.LANCZOS) output_path os.path.join(output_folder, filename) # 保存压缩后的图片 if img.mode RGBA and filename.lower().endswith(.jpg): img img.convert(RGB) img.save(output_path, qualityquality, optimizeTrue) print(f压缩完成{filename} → 大小减少{os.path.getsize(file_path) - os.path.getsize(output_path)}字节)# 使用示例compress_images( folder_path./images, quality75, max_width1920)使用说明安装依赖pip install pillow设置压缩质量和最大宽度即可压缩后图片清晰度基本不受影响体积能减少60%以上。—## 6. 文件夹自动备份脚本场景重要文件需要定期备份避免误删或者硬盘损坏丢失数据。pythonimport shutilimport datetimeimport osdef backup_folder(source_folder, backup_folder./backup): os.makedirs(backup_folder, exist_okTrue) # 用当前时间作为备份文件名 timestamp datetime.datetime.now().strftime(%Y%m%d_%H%M%S) backup_name fbackup_{timestamp}.zip backup_path os.path.join(backup_folder, backup_name) # 压缩备份 shutil.make_archive(backup_path.replace(.zip, ), zip, source_folder) print(f备份完成备份文件{backup_path}) # 自动删除7天前的旧备份 for file in os.listdir(backup_folder): file_path os.path.join(backup_folder, file) if os.path.isfile(file_path) and file.startswith(backup_): create_time os.path.getctime(file_path) if (datetime.datetime.now().timestamp() - create_time) 7 * 24 * 3600: os.remove(file_path) print(f已删除旧备份{file})# 使用示例backup_folder(source_folder./important_files)使用说明可以结合系统定时任务每天自动执行一次备份完全不用手动操作。—## 7. PDF批量转文字脚本场景大量PDF文件需要提取文字内容手动复制太麻烦。pythonimport PyPDF2import osdef pdf_to_text(pdf_path, output_folder./pdf_text): os.makedirs(output_folder, exist_okTrue) filename os.path.basename(pdf_path).replace(.pdf, .txt) output_path os.path.join(output_folder, filename) with open(pdf_path, rb) as f: reader PyPDF2.PdfReader(f) text for page in reader.pages: text page.extract_text() \n\n with open(output_path, w, encodingutf-8) as f: f.write(text) print(f提取完成{os.path.basename(pdf_path)} → {filename})# 批量处理def batch_pdf_to_text(folder_path): for filename in os.listdir(folder_path): if filename.lower().endswith(.pdf): pdf_to_text(os.path.join(folder_path, filename))# 使用示例batch_pdf_to_text(folder_path./pdf_files)使用说明安装依赖pip install pypdf2扫描版PDF需要配合OCR工具使用。—## 8. 系统状态监控脚本场景需要监控服务器的CPU、内存、磁盘使用率超过阈值自动发告警邮件。pythonimport psutilimport timedef monitor_system(threshold_cpu80, threshold_memory80, threshold_disk90): while True: # 获取系统状态 cpu_usage psutil.cpu_percent(interval1) memory_info psutil.virtual_memory() disk_info psutil.disk_usage(/) print(fCPU使用率{cpu_usage}% | 内存使用率{memory_info.percent}% | 磁盘使用率{disk_info.percent}%) # 超过阈值告警 if cpu_usage threshold_cpu: print(f⚠️ 告警CPU使用率超过{threshold_cpu}%) # 这里可以加发送邮件/企业微信/短信告警的逻辑 if memory_info.percent threshold_memory: print(f⚠️ 告警内存使用率超过{threshold_memory}%) if disk_info.percent threshold_disk: print(f⚠️ 告警磁盘使用率超过{threshold_disk}%) time.sleep(60) # 每分钟检查一次# 使用示例monitor_system()使用说明安装依赖pip install psutil可以部署在服务器上24小时运行。—## 9. 验证码自动识别脚本场景登录或者提交表单的时候需要输入验证码不用手动识别。pythonimport ddddocrdef recognize_captcha(image_path): ocr ddddocr.DdddOcr(show_adFalse) with open(image_path, rb) as f: img_bytes f.read() result ocr.classification(img_bytes) print(f验证码识别结果{result}) return result# 使用示例code recognize_captcha(./captcha.png)使用说明安装依赖pip install ddddocr这个库的识别准确率非常高普通数字字母验证码识别率95%以上。—## 10. 短视频无水印下载脚本场景看到好的短视频素材想要保存不用找第三方解析网站。pythonimport requestsimport redef download_video(url, output_path./video): headers { User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1 } response requests.get(url, headersheaders) # 匹配视频地址不同平台规则不同这里以某音为例 video_url re.findall(rplayAddr: ([^]), response.text)[0] video_url video_url.replace(playwm, play) # 去掉水印 video_content requests.get(video_url, headersheaders).content os.makedirs(output_path, exist_okTrue) file_path os.path.join(output_path, f{int(time.time())}.mp4) with open(file_path, wb) as f: f.write(video_content) print(f视频下载完成{file_path})# 使用示例download_video(url短视频分享链接)使用说明不同平台的解析规则不同可以根据需要自行修改匹配规则。—## 写在最后这些脚本都是我日常工作中高频使用的修改一下参数就能直接用。自动化的意义就是把我们从重复劳动里解放出来把时间花在更有价值的事情上。如果觉得有用欢迎点赞收藏有问题可以在评论区交流~ 关注我每周分享实用的开发技巧和效率工具。