
最新動態(tài)
5個Python小程序:高效解決職場日常任務(wù)
2025-01-22作為一名Python開發(fā)者,我深知在日常工作中經(jīng)常遇到一些重復(fù)性的小任務(wù)。今天就來分享我在工作中常用的五個Python小腳本,這些都是經(jīng)過實戰(zhàn)檢驗的“效率神器”。
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:/工作文件/項目文檔")
這個腳本可以按照統(tǒng)一的格式給文件重命名,加上日期和序號,特別適合整理項目文檔。用了這個腳本后,文件管理效率大大提高,同事們也紛紛索要這段代碼。
2. Excel 數(shù)據(jù)處理小助手
作為一名開發(fā)人員,經(jīng)常會收到各種Excel數(shù)據(jù)需要處理。比如上個月,運營部門給我發(fā)來一堆用戶數(shù)據(jù),要求提取特定信息并生成報表。手動復(fù)制粘貼?不存在的!
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)
# 數(shù)據(jù)清洗和處理
df['處理時間'] = datetime.now().strftime('%Y-%m-%d')
# 示例:計算平均值并添加新列
df['平均值'] = df.select_dtypes(include=[np.number]).mean(axis=1)
# 保存處理后的數(shù)據(jù)
df.to_excel(output_file, index=False)
print(f"數(shù)據(jù)處理完成,已保存至:{output_file}")
except Exception as e:
print(f"處理出錯:{str(e)}")
process_excel_data("原始數(shù)據(jù).xlsx", "處理后數(shù)據(jù).xlsx")
這個腳本使用pandas處理Excel數(shù)據(jù),可以根據(jù)實際需求修改處理邏輯?,F(xiàn)在,我?guī)缀跻灰姷紼xcel文件就會掏出這個腳本,稍作修改就能使用。
3. 日志監(jiān)控小幫手
服務(wù)器日志監(jiān)控是一項技術(shù)活,但有時我們只想簡單地監(jiān)控某些關(guān)鍵字。去年線上出現(xiàn)了一次問題,就是因為沒有及時發(fā)現(xiàn)錯誤日志。于是編寫了這個監(jiān)控腳本:
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):
# 發(fā)送郵件告警
pass
# 具體實現(xiàn)省略
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()
這個腳本可以實時監(jiān)控日志文件,發(fā)現(xiàn)關(guān)鍵字后立即發(fā)送告警郵件。配合系統(tǒng)定時任務(wù)使用,基本上可以實現(xiàn)7×24小時的監(jiān)控。
4. 圖片壓縮小工具
前段時間做了一個小程序,產(chǎn)品經(jīng)理總是抱怨圖片上傳太慢。檢查后發(fā)現(xiàn)很多圖片都是原圖上傳的,動輒好幾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庫進(jìn)行圖片壓縮,可以批量處理整個目錄的圖片,且保持不錯的畫質(zhì)。最近我還加了一個自動判斷是否需要壓縮的功能,如果圖片本身已經(jīng)足夠小,就跳過,以免重復(fù)壓縮。
5. 定時備份小助手
數(shù)據(jù)備份的重要性誰都知道,但真正建立起備份機(jī)制的人卻不多。我見過多次因未備份而導(dǎo)致加班的慘劇。這是我編寫的一個自動備份腳本:
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:
# 創(chuàng)建備份
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}")
# 設(shè)置定時任務(wù)
schedule.every().day.at("02:00").do(
backup_files,
"D:/重要文件",
"E:/備份"
)
# 運行定時任務(wù)
while True:
schedule.run_pending()
time.sleep(60)
這個腳本會在每天凌晨兩點自動運行備份,并且會自動清理舊的備份文件,避免占用過多存儲空間。
總結(jié)
這些腳本都是我在實際工作中經(jīng)常用到的,它們幫助我節(jié)省了大量的重復(fù)性工作時間。當(dāng)然,這些代碼還有很多可以優(yōu)化的地方,比如可以加入更多的異常處理、日志記錄等。
建議大家根據(jù)自己的實際需求,對這些腳本進(jìn)行修改和完善。記住,寫腳本的目的是為了提高工作效率,而不是為了炫耀。只要能解決問題,簡單實用就好。
如果你也有一些好用的Python腳本,歡迎在評論區(qū)分享出來。