本文目录导读:

提升日常工作效率的脚本通常聚焦于自动化重复性任务、文件管理、数据处理和系统维护,以下是一些实用且易于上手的脚本示例(以 Python 和 Shell 为主),你可以根据需求调整使用:
文件与文件夹管理
批量重命名文件(Python)
import os
def batch_rename(path, prefix=""):
""" 将文件夹内所有文件按 "前缀_序号.ext" 重命名 """
for i, filename in enumerate(os.listdir(path)):
src = os.path.join(path, filename)
if os.path.isfile(src):
ext = os.path.splitext(filename)[1]
dst = os.path.join(path, f"{prefix}_{i+1}{ext}")
os.rename(src, dst)
print(f"重命名: {filename} -> {os.path.basename(dst)}")
# 使用示例:批量重命名当前文件夹下的图片
batch_rename("./photos", prefix="pic")
自动整理下载文件夹(Python)
import os
import shutil
ext_dirs = {
'图片': ['.jpg','.jpeg','.png','.gif'],
'文档': ['.pdf','.docx','.xlsx','.txt'],
'压缩包': ['.zip','.rar','.7z','.tar'],
'视频': ['.mp4','.avi','.mkv'],
'音频': ['.mp3','.wav','.flac']
}
def organize_downloads(download_path):
for file in os.listdir(download_path):
file_path = os.path.join(download_path, file)
if os.path.isfile(file_path):
ext = os.path.splitext(file)[1].lower()
for category, exts in ext_dirs.items():
if ext in exts:
target_dir = os.path.join(download_path, category)
os.makedirs(target_dir, exist_ok=True)
shutil.move(file_path, os.path.join(target_dir, file))
print(f"移动 {file} 到 {category}")
break
# 运行:整理 ~/Downloads
organize_downloads(os.path.expanduser("~/Downloads"))
系统维护与监控
一键清理系统垃圾(Bash / Linux)
#!/bin/bash # clean_sys.sh echo "清理系统缓存和临时文件..." sudo apt-get autoremove -y # 移除孤立的软件包 sudo apt-get autoclean # 清理旧软件包缓存 rm -rf ~/.cache/* # 清除用户缓存 rm -rf /tmp/* # 清空临时目录 echo "磁盘空间释放完成!" df -h / # 查看根分区使用情况
检测并杀死高CPU进程(Python + psutil)
import psutil
import os
def kill_high_cpu_processes(threshold=80):
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
try:
cpu = proc.info['cpu_percent']
if cpu and cpu > threshold:
print(f"发现高CPU进程: {proc.info['name']} (PID={proc.info['pid']}) CPU={cpu}%")
# 可以选择结束进程(谨慎使用)
# proc.kill()
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
# 每5分钟执行一次监控(需安装psutil: pip install psutil)
import time
while True:
kill_high_cpu_processes(threshold=85)
time.sleep(300)
文本与数据处理
批量转换Excel为CSV(Python)
import pandas as pd
import os
def convert_xlsx_to_csv(folder_path):
for file in os.listdir(folder_path):
if file.endswith('.xlsx') or file.endswith('.xls'):
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path, engine='openpyxl')
csv_name = os.path.splitext(file)[0] + '.csv'
df.to_csv(os.path.join(folder_path, csv_name), index=False)
print(f"转换完成: {file} -> {csv_name}")
# 运行:转换当前目录下所有Excel
convert_xlsx_to_csv(".")
快速提取网页正文内容(Python)
import requests
from bs4 import BeautifulSoup
def extract_article_text(url):
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(response.text, 'html.parser')
# 尝试获取正文(常见标签)
article = soup.find('article') or soup.find('div', class_='content') or soup.find('body')
if article:
text = article.get_text(strip=True)
return text[:500] + "..." # 截取前500字符作为预览
return "未能提取到正文。"
print(extract_article_text("https://example.com/news"))
自动化提醒与定时任务
番茄钟 + 桌面通知(Python)
import time
from plyer import notification
def pomodoro_timer(work_min=25, break_min=5):
while True:
notification.notify(
title="🍅 番茄钟",
message=f"专注工作 {work_min} 分钟开始!",
timeout=5
)
time.sleep(work_min * 60)
notification.notify(
title="⏰ 休息时间",
message=f"休息 {break_min} 分钟,放松一下~",
timeout=5
)
time.sleep(break_min * 60)
# 注意:需安装 plyer: pip install plyer
定时备份指定文件夹(Bash + cron)
#!/bin/bash # backup_script.sh src="/home/user/documents" dest="/backup/documents_$(date +%Y%m%d_%H%M%S).tar.gz" tar czf "$dest" "$src" && echo "备份完成: $dest"
然后在系统中添加cron任务(crontab -e):
0 2 * * * /path/to/backup_script.sh # 每天凌晨2点备份
日常快捷操作
快速打开常用网址(Bash别名)加入 ~/.bashrc 或 ~/.zshrc:
alias gg='google-chrome https://github.com' # 打开GitHub alias gm='firefox https://gmail.com' # 打开Gmail alias news='w3m https://news.ycombinator.com' # 终端浏览Hacker News
OCR截图转文字(Python)
import pyautogui
import pyperclip
import pytesseract
from PIL import Image
def ocr_from_screenshot():
# 截图
screenshot = pyautogui.screenshot()
# 识别文字(需安装 tesseract-ocr 和 pytesseract)
text = pytesseract.image_to_string(screenshot, lang='chi_sim+eng')
pyperclip.copy(text.strip())
print("文字已复制到剪贴板!")
ocr_from_screenshot()
使用建议
- 安全第一:涉及删除或修改系统文件的脚本(尤其带
sudo或shutil.rmtree),务必先测试或添加确认步骤。 - 环境准备:Python脚本需要依赖库时,建议创建虚拟环境(
python -m venv myenv)再安装pip install。 - 定制化:根据具体需求调整路径、阈值、文件类型等参数。
- 定时执行:利用系统任务调度工具(Linux的cron、Windows的任务计划程序)让脚本自动运行。
扩展思路
- 邮件自动化:用
smtplib发送日报/周报摘要 - 网络监控:检测网站是否正常并推送告警(
requests+pushover) - 数据爬虫:定时抓取特定信息(如天气、股票价格)并写入文件
如果你有更具体的场景(如处理PDF、制作报告、视频剪辑预处理等),可以进一步提供细节,我会给出针对性脚本建议。