一文分享10个让你效率翻10倍的Python脚本(拿来直接用)
作者:Lumi_Peak
前言
你有没有算过,每天有多少时间浪费在重复劳动上?
- 复制粘贴文件名
- 手动修改Excel表格
- 一个个下载网页图片
- 手动发送相同内容的邮件
- …
这些看似简单的操作,一天下来可能要消耗你2-3小时。
今天这篇文章,我整理了10个最实用的Python自动化脚本,覆盖文件处理、数据操作、网络请求、自动化办公等多个场景。每个脚本都提供完整代码和使用说明,直接复制就能用。
准备好让你的效率翻10倍了吗?开始吧!
脚本1:批量提取文件名
适用场景
需要把某个文件夹下所有文件名导出到Excel或记事本,比如:
- 整理素材库,生成文件清单
- 做资产盘点,统计文件数量
- 批量操作时,需要先知道有哪些文件
核心代码
import os
def extract_filenames(folder_path, output_file):
"""
提取文件夹内所有文件名并保存
参数:
folder_path: 目标文件夹路径
output_file: 输出文件路径(.txt或.xlsx)
"""
# 获取所有文件名
filenames = []
for root, dirs, files in os.walk(folder_path):
for file in files:
full_path = os.path.join(root, file)
relative_path = os.path.relpath(full_path, folder_path)
filenames.append(relative_path)
# 保存到文件
with open(output_file, 'w', encoding='utf-8') as f:
for name in filenames:
f.write(name + '\n')
print(f'已提取 {len(filenames)} 个文件名,保存到: {output_file}')
# 使用示例
extract_filenames(r'C:\项目资料', '文件清单.txt')
效率提升: 手动复制:10分钟 → 脚本执行:5秒,效率提升 120倍
脚本2:自动创建文件夹结构
适用场景
项目启动时需要创建固定的文件夹结构,比如:
项目/
├── 01_需求文档/
├── 02_设计稿/
├── 03_开发文档/
├── 04_测试报告/
└── 05_交付文档/
核心代码
import os
def create_project_structure(base_path, structure):
"""
根据配置创建文件夹结构
参数:
base_path: 根目录路径
structure: 文件夹结构(列表或字典)
"""
def create_folder(path):
if not os.path.exists(path):
os.makedirs(path)
print(f'创建文件夹: {path}')
if isinstance(structure, dict):
for folder, subfolders in structure.items():
folder_path = os.path.join(base_path, folder)
create_folder(folder_path)
if subfolders:
create_project_structure(folder_path, subfolders)
elif isinstance(structure, list):
for folder in structure:
folder_path = os.path.join(base_path, folder)
create_folder(folder_path)
print('\n文件夹结构创建完成!')
# 使用示例
project_structure = {
'01_需求文档': ['原始需求', '需求分析', '原型图'],
'02_设计稿': ['UI设计', '交互设计'],
'03_开发文档': ['技术方案', '接口文档'],
'04_测试报告': ['测试用例', '测试结果'],
'05_交付文档': ['用户手册', '部署文档']
}
create_project_structure(r'D:\新项目', project_structure)
效率提升: 手动创建:5分钟 → 脚本执行:1秒,效率提升 300倍
脚本3:批量转换图片格式
适用场景
需要把PNG转JPG,或者压缩图片体积,比如:
- 网站素材需要统一格式
- 减小图片体积方便传输
核心代码
from PIL import Image
import os
def convert_images(input_folder, output_folder, target_format='jpg'):
"""
批量转换图片格式
参数:
input_folder: 输入文件夹
output_folder: 输出文件夹
target_format: 目标格式(jpg/png/webp)
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.webp', '.gif']
converted = 0
for filename in os.listdir(input_folder):
if any(filename.lower().endswith(ext) for ext in supported_formats):
try:
img_path = os.path.join(input_folder, filename)
img = Image.open(img_path)
# 处理透明通道(PNG转JPG时需要)
if img.mode == 'RGBA':
img = img.convert('RGB')
new_name = os.path.splitext(filename)[0] + f'.{target_format}'
output_path = os.path.join(output_folder, new_name)
img.save(output_path, target_format.upper())
converted += 1
print(f'转换成功: {filename} -> {new_name}')
except Exception as e:
print(f'转换失败: {filename}, 错误: {e}')
print(f'\n转换完成!共处理 {converted} 张图片')
# 使用示例
convert_images(r'C:\原始图片', r'C:\转换后图片', 'jpg')
依赖: pip install Pillow 效率提升: 使用PS手动转换:30分钟 → 脚本执行:10秒,效率提升 180倍
脚本4:批量下载网页图片
适用场景
看到网页上有好看的图片,想一键全部下载,比如:
- 设计参考图收集
- 素材下载
- 竞品分析资料
核心代码
import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urljoin
def download_images_from_web(url, output_folder):
"""
下载网页中所有图片
参数:
url: 网页地址
output_folder: 保存文件夹
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
downloaded = 0
for i, img in enumerate(images):
try:
img_url = img.get('src') or img.get('data-src')
if not img_url:
continue
if not img_url.startswith('http'):
img_url = urljoin(url, img_url)
img_response = requests.get(img_url, headers=headers, timeout=10)
ext = os.path.splitext(img_url)[1] or '.jpg'
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
ext = '.jpg'
filename = f'image_{i+1:03d}{ext}'
filepath = os.path.join(output_folder, filename)
with open(filepath, 'wb') as f:
f.write(img_response.content)
downloaded += 1
print(f'下载成功: {filename}')
except Exception as e:
print(f'下载失败: {img_url[:50]}... 错误: {e}')
print(f'\n下载完成!共下载 {downloaded} 张图片')
# 使用示例
download_images_from_web('https://example.com/gallery', r'C:\下载图片')
依赖: pip install requests beautifulsoup4 效率提升: 手动右键另存:20分钟 → 脚本执行:15秒,效率提升 80倍
脚本5:自动发送邮件
适用场景
需要定期发送相同内容的邮件,比如:
- 工作日报
- 通知邮件
- 营销邮件(请勿滥用)
核心代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(config):
"""
发送邮件(支持附件)
参数:
config: 邮件配置字典
- sender: 发件人邮箱
- password: 邮箱授权码(不是登录密码)
- receiver: 收件人邮箱
- subject: 邮件主题
- content: 邮件内容
- attachments: 附件列表(可选)
"""
msg = MIMEMultipart()
msg['From'] = config['sender']
msg['To'] = config['receiver']
msg['Subject'] = config['subject']
msg.attach(MIMEText(config['content'], 'plain', 'utf-8'))
if 'attachments' in config:
for file_path in config['attachments']:
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
f'attachment; filename="{os.path.basename(file_path)}"')
msg.attach(part)
try:
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
server.login(config['sender'], config['password'])
server.sendmail(config['sender'], config['receiver'], msg.as_string())
server.quit()
print('邮件发送成功!')
except Exception as e:
print(f'邮件发送失败: {e}')
# 使用示例
email_config = {
'sender': 'your_email@qq.com',
'password': 'your_authorization_code', # 在邮箱设置中获取授权码
'receiver': 'target@example.com',
'subject': '工作日报 - 2024/01/15',
'content': '今日工作内容:\n1. 完成A模块开发\n2. 修复B问题\n3. 编写测试用例',
'attachments': [r'C:\日报.xlsx']
}
send_email(email_config)
注意: QQ邮箱需要授权码,在邮箱设置→账户→POP3/SMTP服务中获取 效率提升: 手动发邮件:5分钟 → 脚本执行:3秒,效率提升 100倍
脚本6:批量压缩文件
适用场景
需要把多个文件或文件夹压缩打包,比如:
- 项目归档
- 文件传输
- 备份资料
核心代码
import zipfile
import os
def batch_compress(source_paths, output_file):
"""
批量压缩文件或文件夹
参数:
source_paths: 要压缩的文件/文件夹列表
output_file: 输出压缩包路径
"""
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for source in source_paths:
if os.path.isfile(source):
zipf.write(source, os.path.basename(source))
print(f'添加文件: {source}')
elif os.path.isdir(source):
folder_name = os.path.basename(source)
for root, dirs, files in os.walk(source):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.join(folder_name, os.path.relpath(file_path, source))
zipf.write(file_path, arcname)
print(f'添加文件夹: {source}')
size = os.path.getsize(output_file) / 1024 / 1024
print(f'\n压缩完成!文件大小: {size:.2f} MB')
print(f'保存位置: {output_file}')
# 使用示例
sources = [
r'C:\项目文档',
r'C:\设计稿',
r'C:\需求说明.pdf'
]
batch_compress(sources, r'C:\项目备份.zip')
效率提升: 手动右键压缩:3分钟 → 脚本执行:10秒,效率提升 18倍
脚本7:自动清理临时文件
适用场景
系统运行久了产生大量临时文件,占用磁盘空间,比如:
- 浏览器缓存
- 系统临时文件
- 软件产生的日志文件
核心代码
import os
import shutil
def clean_temp_files(folders_to_clean, extensions_to_delete=None):
"""
清理临时文件
参数:
folders_to_clean: 要清理的文件夹列表
extensions_to_delete: 要删除的文件扩展名列表(可选)
"""
total_deleted = 0
total_size = 0
for folder in folders_to_clean:
if not os.path.exists(folder):
print(f'文件夹不存在: {folder}')
continue
print(f'\n正在清理: {folder}')
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
if extensions_to_delete:
ext = os.path.splitext(file)[1].lower()
if ext not in extensions_to_delete:
continue
try:
size = os.path.getsize(file_path)
os.remove(file_path)
total_deleted += 1
total_size += size
print(f'删除: {file_path}')
except Exception as e:
print(f'删除失败: {file_path}, 原因: {e}')
print(f'\n清理完成!删除文件: {total_deleted} 个,释放空间: {total_size / 1024 / 1024:.2f} MB')
# 使用示例
temp_folders = [
os.environ.get('TEMP'),
r'C:\Windows\Temp',
os.path.expanduser('~\AppData\Local\Microsoft\Windows\INetCache')
]
extensions = ['.tmp', '.log', '.cache', '.bak']
clean_temp_files(temp_folders, extensions)
注意: 建议先备份重要文件,不要删除正在使用的程序文件 效率提升: 手动查找删除:15分钟 → 脚本执行:30秒,效率提升 30倍
脚本8:批量修改文件时间戳
适用场景
需要统一文件的创建/修改时间,比如:
- 整理照片按日期排序
- 统一项目文件时间
- 数据归档整理
核心代码
import os
import time
def modify_file_timestamp(folder_path, target_date):
"""
批量修改文件时间戳
参数:
folder_path: 目标文件夹
target_date: 目标日期字符串(格式:'2024-01-15 12:00:00')
"""
target_timestamp = time.mktime(time.strptime(target_date, '%Y-%m-%d %H:%M:%S'))
modified_count = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
try:
os.utime(file_path, (target_timestamp, target_timestamp))
modified_count += 1
print(f'修改: {file}')
except Exception as e:
print(f'修改失败: {file_path}, 原因: {e}')
print(f'\n修改完成!共处理 {modified_count} 个文件')
# 使用示例
modify_file_timestamp(r'C:\项目文档', '2024-01-15 09:00:00')
效率提升: 手动修改:不支持 → 脚本执行:5秒
脚本9:Excel数据对比工具
适用场景
需要对比两个Excel表格的差异,比如:
- 检查数据变更
- 核对账目差异
- 版本对比
核心代码
import pandas as pd
def compare_excel(file1, file2, output_file):
"""
对比两个Excel文件并输出差异
参数:
file1: 第一个Excel文件
file2: 第二个Excel文件
output_file: 差异报告输出路径
"""
df1 = pd.read_excel(file1)
df2 = pd.read_excel(file2)
common_cols = list(set(df1.columns) & set(df2.columns))
if not common_cols:
print('两个文件没有共同的列!')
return
differences = []
for col in common_cols:
diff = df1[col] != df2[col]
if diff.any():
diff_rows = df1[diff].index.tolist()
for row in diff_rows:
differences.append({
'行号': row + 2,
'列名': col,
'文件1的值': df1.loc[row, col] if row < len(df1) else 'N/A',
'文件2的值': df2.loc[row, col] if row < len(df2) else 'N/A'
})
if differences:
diff_df = pd.DataFrame(differences)
diff_df.to_excel(output_file, index=False)
print(f'发现 {len(differences)} 处差异,已保存到: {output_file}')
else:
print('两个文件内容完全一致!')
# 使用示例
compare_excel(
r'C:\原始数据.xlsx',
r'C:\修改后数据.xlsx',
r'C:\差异报告.xlsx'
)
效率提升: 手动逐行对比:40分钟 → 脚本执行:3秒,效率提升 800倍
脚本10:定时任务执行器
适用场景
需要定时执行某个脚本或任务,比如:
- 定时备份数据
- 定时发送报告
- 定时清理文件
核心代码
import schedule
import time
import subprocess
def run_task(task_name, command):
"""执行任务"""
print(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] 开始执行: {task_name}')
try:
subprocess.run(command, shell=True, check=True)
print(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] 执行完成: {task_name}')
except Exception as e:
print(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] 执行失败: {e}')
def setup_scheduled_tasks(tasks):
"""
设置定时任务
参数:
tasks: 任务配置列表
"""
for task in tasks:
name = task['name']
cmd = task['command']
if task['schedule_type'] == 'daily':
schedule.every().day.at(task['time']).do(run_task, name, cmd)
print(f'已设置每日任务: {name} @ {task["time"]}')
elif task['schedule_type'] == 'weekly':
day = task.get('day', 'monday')
getattr(schedule.every(), day).at(task['time']).do(run_task, name, cmd)
print(f'已设置每周任务: {name} @ {day} {task["time"]}')
elif task['schedule_type'] == 'interval':
minutes = task.get('minutes', 60)
schedule.every(minutes).minutes.do(run_task, name, cmd)
print(f'已设置周期任务: {name} @ 每{minutes}分钟')
print('\n定时任务已启动,按 Ctrl+C 停止...\n')
while True:
schedule.run_pending()
time.sleep(1)
# 使用示例
tasks_config = [
{'name': '数据备份', 'command': 'python backup.py', 'schedule_type': 'daily', 'time': '18:00'},
{'name': '清理临时文件', 'command': 'python clean_temp.py', 'schedule_type': 'daily', 'time': '23:00'},
{'name': '发送日报', 'command': 'python send_report.py', 'schedule_type': 'daily', 'time': '17:30'}
]
setup_scheduled_tasks(tasks_config)
依赖: pip install schedule 效率提升: 无需人工干预,全自动执行,效率提升 ∞
总结:效率提升对比表
| 脚本 | 手动时间 | 脚本时间 | 效率提升 |
|---|---|---|---|
| 提取文件名 | 10分钟 | 5秒 | 120倍 |
| 创建文件夹结构 | 5分钟 | 1秒 | 300倍 |
| 转换图片格式 | 30分钟 | 10秒 | 180倍 |
| 下载网页图片 | 20分钟 | 15秒 | 80倍 |
| 发送邮件 | 5分钟 | 3秒 | 100倍 |
| 压缩文件 | 3分钟 | 10秒 | 18倍 |
| 清理临时文件 | 15分钟 | 30秒 | 30倍 |
| 修改时间戳 | 不支持 | 5秒 | ∞ |
| Excel对比 | 40分钟 | 3秒 | 800倍 |
| 定时任务 | 需人工 | 自动 | ∞ |
平均效率提升:200倍+
使用建议
- 先跑通一个脚本:选择最需要的场景,复制代码测试
- 根据需求修改:调整参数、路径,适应你的场景
- 建立自己的脚本库:把常用脚本整理成文件夹
- 持续优化:遇到问题就改,越用越顺手
以上就是一文分享10个让你效率翻10倍的Python脚本(拿来直接用)的详细内容,更多关于Python自动化脚本的资料请关注脚本之家其它相关文章!
