5个Python小程序:高效解决职场日常任务
2025-01-22作为一名Python开发者,我深知在日常工作中经常遇到一些重复性的小任务。今天就来分享我在工作中常用的五个Python小脚本,这些都是经过实战检验的“效率神器”。
1. 批量重命名文件小能手
记得去年接手一个项目时,接收到了一堆命名混乱的文档和图片文件。有的是中文,有的是英文,还有一些奇奇怪怪的字符。要是手动改名字,估计得花费半天时间。于是编写了这样一个小脚本:
import os
import re
from datetime import datetime
def batch_rename_files(directory, prefix='file_'):
if not os.path.exists(directory):
print(f"目录 {directory} 不存在!")
return
for index, filename in enumerate(os.listdir(directory)):
file_ext = os.path.splitext(filename)[1]
new_name = f"{prefix}{datetime.now().strftime('%Y%m%d')}_{index}{file_ext}"
old_file = os.path.join(directory, filename)
new_file = os.path.join(directory, new_name)
os.rename(old_file, new_file)
print(f"已将 {filename} 重命名为 {new_name}")
batch_rename_files("D:/工作文件/项目文档")
这个脚本可以按照统一的格式给文件重命名,加上日期和序号,特别适合整理项目文档。用了这个脚本后,文件管理效率大大提高,同事们也纷纷索要这段代码。
2. Excel 数据处理小助手
作为一名开发人员,经常会收到各种Excel数据需要处理。比如上个月,运营部门给我发来一堆用户数据,要求提取特定信息并生成报表。手动复制粘贴?不存在的!
import pandas as pd
import numpy as np
from datetime import datetime
def process_excel_data(input_file, output_file):
try:
# 读取Excel文件
df = pd.read_excel(input_file)
# 数据清洗和处理
df['处理时间'] = datetime.now().strftime('%Y-%m-%d')
# 示例:计算平均值并添加新列
df['平均值'] = df.select_dtypes(include=[np.number]).mean(axis=1)
# 保存处理后的数据
df.to_excel(output_file, index=False)
print(f"数据处理完成,已保存至:{output_file}")
except Exception as e:
print(f"处理出错:{str(e)}")
process_excel_data("原始数据.xlsx", "处理后数据.xlsx")
这个脚本使用pandas处理Excel数据,可以根据实际需求修改处理逻辑。现在,我几乎一见到Excel文件就会掏出这个脚本,稍作修改就能使用。
3. 日志监控小帮手
服务器日志监控是一项技术活,但有时我们只想简单地监控某些关键字。去年线上出现了一次问题,就是因为没有及时发现错误日志。于是编写了这个监控脚本:
import time
import re
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import smtplib
from email.mime.text import MIMEText
class LogWatcher(FileSystemEventHandler):
def __init__(self, keywords, email_config):
self.keywords = keywords
self.email_config = email_config
def on_modified(self, event):
if event.src_path.endswith('.log'):
self.check_log_content(event.src_path)
def check_log_content(self, log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
# 只读取最后1000行
lines = f.readlines()[-1000:]
for line in lines:
if any(keyword in line for keyword in self.keywords):
self.send_alert(line)
except Exception as e:
print(f"读取日志出错:{str(e)}")
def send_alert(self, content):
# 发送邮件告警
pass
# 具体实现省略
keywords = ["Error", "Exception", "Failed"]
email_config = {
"smtp_server": "smtp.company.com",
"sender": "alert@company.com",
"password": "****",
"receiver": "your@email.com"
}
observer = Observer()
observer.schedule(LogWatcher(keywords, email_config), '/logs/', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
这个脚本可以实时监控日志文件,发现关键字后立即发送告警邮件。配合系统定时任务使用,基本上可以实现7×24小时的监控。
4. 图片压缩小工具
前段时间做了一个小程序,产品经理总是抱怨图片上传太慢。检查后发现很多图片都是原图上传的,动辄好几MB。于是编写了这个批量压缩的脚本:
from PIL import Image
import os
def compress_images(input_dir, output_dir, quality=85):
# 确保输出目录存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 支持的图片格式
supported_formats = ['.jpg', '.jpeg', '.png']
# 遍历目录下的所有文件
for filename in os.listdir(input_dir):
if any(filename.lower().endswith(fmt) for fmt in supported_formats):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
# 打开图片
with Image.open(input_path) as img:
# 保存压缩后的图片
img.save(output_path, quality=quality, optimize=True)
# 计算压缩比例
original_size = os.path.getsize(input_path)
compressed_size = os.path.getsize(output_path)
ratio = (original_size - compressed_size) / original_size * 100
print(f"压缩 {filename} 完成,压缩率:{ratio:.2f}%")
compress_images("原始图片", "压缩后图片")
这个脚本使用Pillow库进行图片压缩,可以批量处理整个目录的图片,且保持不错的画质。最近我还加了一个自动判断是否需要压缩的功能,如果图片本身已经足够小,就跳过,以免重复压缩。
5. 定时备份小助手
数据备份的重要性谁都知道,但真正建立起备份机制的人却不多。我见过多次因未备份而导致加班的惨剧。这是我编写的一个自动备份脚本:
import shutil
import os
from datetime import datetime
import schedule
import time
def 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}")
try:
# 创建备份
shutil.copytree(source_dir, backup_path)
# 清理旧备份,只保留最近7天的
cleanup_old_backups(backup_dir, days=7)
print(f"备份完成:{backup_path}")
except Exception as e:
print(f"备份失败:{str(e)}")
def cleanup_old_backups(backup_dir, days):
# 清理旧备份文件
current_time = datetime.now()
for item in os.listdir(backup_dir):
item_path = os.path.join(backup_dir, item)
created_time = datetime.fromtimestamp(os.path.getctime(item_path))
if (current_time - created_time).days > days:
shutil.rmtree(item_path)
print(f"已清理旧备份:{item}")
# 设置定时任务
schedule.every().day.at("02:00").do(
backup_files,
"D:/重要文件",
"E:/备份"
)
# 运行定时任务
while True:
schedule.run_pending()
time.sleep(60)
这个脚本会在每天凌晨两点自动运行备份,并且会自动清理旧的备份文件,避免占用过多存储空间。
总结
这些脚本都是我在实际工作中经常用到的,它们帮助我节省了大量的重复性工作时间。当然,这些代码还有很多可以优化的地方,比如可以加入更多的异常处理、日志记录等。
建议大家根据自己的实际需求,对这些脚本进行修改和完善。记住,写脚本的目的是为了提高工作效率,而不是为了炫耀。只要能解决问题,简单实用就好。
如果你也有一些好用的Python脚本,欢迎在评论区分享出来。