下载目录里 300 多个文件,名字乱得像事故现场;几十份 Excel 等着合并;日志里找一个报错,手动翻到眼睛疼。这种活我现在基本不愿意手点。
能写个 Python 脚本跑掉的事情,重复做第二遍我都觉得亏。
下面这 10 个脚本,都是我平时更愿意留在 tools 目录里的那种东西。代码不复杂,但真能省时间。
1. 下载目录自动归档
我最烦桌面和下载目录堆满 PDF、压缩包、图片。按扩展名直接分目录,跑一次就清净了。
from pathlib import Path
import shutil
root = Path.home() / "Downloads"
rules = {
".pdf": "PDF",
".xlsx": "Excel",
".zip": "Archive",
".png": "Images",
".jpg": "Images",
}
for f in root.iterdir():
ifnot f.is_file():
continue
folder = rules.get(f.suffix.lower())
ifnot folder:
continue
target = root / folder
target.mkdir(exist_ok=True)
shutil.move(str(f), target / f.name)
这种脚本我一般不追求“支持所有格式”。自己天天碰到哪几种,就收拾哪几种。
2. 批量给文件重命名
有些系统导出来的文件名特别离谱:
IMG_20260817_00123.jpg
IMG_20260817_00124.jpg
要发给别人时,我通常直接按顺序重排。
from pathlib import Path
folder = Path("./screenshots")
for no, file in enumerate(sorted(folder.glob("*.jpg")), 1):
new_name = folder / f"接口截图_{no:03d}.jpg"
file.rename(new_name)
比在资源管理器里一个个按 F2 强多了。
3. 合并一堆 CSV
运营一次扔过来十几个 CSV,我第一反应一般不是打开 Excel,而是先看字段是不是一样。
字段一致,直接合。
import csv
from pathlib import Path
files = list(Path("./data").glob("*.csv"))
with open("merged.csv", "w", newline="", encoding="utf-8-sig") as out:
writer = None
for file in files:
with file.open(encoding="utf-8-sig") as src:
reader = csv.DictReader(src)
if writer isNone:
writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
writer.writeheader()
writer.writerows(reader)
数据量不大时,标准库就够了,没必要见个表格就先上 pandas。
4. 从日志里捞 ERROR
线上日志几十 MB,直接拿编辑器开,我是不太喜欢这么干的。
先把 ERROR 和异常上下文捞出来再说。
from pathlib import Path
log = Path("service.log")
hit = Path("error_only.log")
with log.open(encoding="utf-8", errors="ignore") as src, \
hit.open("w", encoding="utf-8") as out:
for line in src:
if" ERROR "in line or"Traceback"in line:
out.write(line)
真排问题时还能继续加 traceId、接口路径、订单号这些条件。
日志排查很多时候不是“看更多”,而是先把没用的东西扔掉。
5. 批量检查接口是不是活着
测试环境服务一多,最烦的就是挨个浏览器访问。
我一般留个健康检查脚本。
from urllib.request import urlopen
from urllib.error import URLError
services = {
"用户服务": "http://127.0.0.1:8001/health",
"订单服务": "http://127.0.0.1:8002/health",
"库存服务": "http://127.0.0.1:8003/health",
}
for name, url in services.items():
try:
with urlopen(url, timeout=2) as resp:
print(name, resp.status)
except URLError as e:
print(name, "FAILED", e.reason)
谁挂了,一眼就知道。
6. 自动清理过期日志
这种脚本一定要小心,我最不喜欢 rm -rf 式豪迈代码。
先限制目录,再限制后缀,再判断时间。
from pathlib import Path
import time
log_dir = Path("/opt/app/logs")
expire_before = time.time() - 15 * 24 * 3600
for file in log_dir.glob("*.log"):
if file.is_file() and file.stat().st_mtime < expire_before:
print("delete:", file)
file.unlink()
第一次跑我甚至会把 unlink() 注释掉,只打印文件。确认没删错,再真动手。
这种地方怂一点不丢人。
7. 批量替换配置
几十个配置文件都要改一个域名,手改基本等着漏。
from pathlib import Path
old = "api-old.internal"
new = "api-new.internal"
for file in Path("./configs").rglob("*.yaml"):
text = file.read_text(encoding="utf-8")
if old notin text:
continue
file.write_text(text.replace(old, new), encoding="utf-8")
print("updated:", file)
我会特意加 if old not in text。
不是为了性能,是为了最后打印出来的东西干净,方便核对到底改了哪些文件。
8. 检查重复数据
导入用户、订单、设备编号之前,我一般先跑一遍重复检查。
import csv
from collections import Counter
with open("users.csv", encoding="utf-8-sig") as f:
rows = csv.DictReader(f)
emails = [row["email"].strip().lower() for row in rows]
for email, count in Counter(emails).items():
if count > 1:
print(count, email)
很多导入事故,其实根本不用等数据库报唯一键冲突。
文件拿到手的时候就能发现。
9. 自动备份指定目录
重要的小脚本、SQL、配置文件,我不太信“等有空了再备份”。
让机器自己压。
from pathlib import Path
from datetime import datetime
import shutil
source = Path("./work")
backup_dir = Path("./backup")
backup_dir.mkdir(exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M")
target = backup_dir / f"work_{stamp}"
shutil.make_archive(str(target), "zip", source)
print(target.with_suffix(".zip"))
再配个 cron 或 Windows 任务计划,基本不用管。
10. 找出目录里的大文件
磁盘突然爆满时,我一般不急着装什么分析工具。
Python 先扫一遍,经常一分钟内就能看到谁在搞事。
from pathlib import Path
root = Path("/opt/app")
files = (
f for f in root.rglob("*")
if f.is_file()
)
top = sorted(
files,
key=lambda f: f.stat().st_size,
reverse=True
)[:10]
for file in top:
size_mb = file.stat().st_size / 1024 / 1024
print(f"{size_mb:8.1f} MB {file}")
真遇到过日志忘了滚动,一个文件悄悄长到几个 GB。服务本身没挂,磁盘先给干满了。
Python 做日常自动化,我一直觉得没必要一上来就搞什么“大型自动化平台”。
先盯住那些你每天都在重复点鼠标、复制文件、筛日志、改配置的动作。
一个几十行的小脚本,只要稳定替你干半年,已经值回票价了。
我自己的判断很简单:同一件机械操作做到第三次,就该考虑让 Python 接手了。