前言
每天下载的文件堆满桌面,.zip、.pdf、.jpg 混在一起,想找的时候翻半天。这件事其实完全可以交给脚本处理——今天我们就用 python 写一个桌面文件自动整理器,按文件类型自动分类到不同文件夹,全程无依赖、开箱即用。
这个脚本虽然只有 60 行代码,但涉及路径操作、正则匹配、日志记录三个实用技能,学会了可以扩展到任何批量文件处理场景。
主题介绍
我们要实现的功能:
- 扫描指定目录(默认桌面)的所有文件
- 根据文件扩展名将文件移动到对应的分类文件夹(文档、图片、视频、压缩包、代码等)
- 记录每次操作日志,方便回查
- 同名文件自动加后缀避免覆盖
核心思路:用 os 和 shutil 模块完成移动,用字典映射扩展名到分类,用 logging 记录轨迹。
环境准备
- python 3.8+(系统自带即可,无需第三方库)
- windows 桌面路径:
c:\users\用户名\desktop - macos 桌面路径:
~/desktop - linux 桌面路径:
~/desktop
创建项目目录结构:
mkdir ~/desktop-organizer cd ~/desktop-organizer touch organizer.py organize_log.json
实操步骤
步骤 1:定义分类规则
先建一个扩展名到文件夹名的映射字典。这是整个脚本的核心配置:
# 扩展名 → 目标文件夹名
category_map = {
"pdf": "文档",
"doc": "文档", "docx": "文档", "txt": "文档", "md": "文档",
"jpg": "图片", "jpeg": "图片", "png": "图片", "gif": "图片",
"svg": "图片", "webp": "图片", "bmp": "图片",
"mp4": "视频", "mov": "视频", "avi": "视频", "mkv": "视频",
"mp3": "音频", "wav": "音频", "flac": "音频",
"zip": "压缩包", "rar": "压缩包", "7z": "压缩包", "tar.gz": "压缩包",
"py": "代码", "js": "代码", "html": "代码", "css": "代码",
"exe": "可执行", "dmg": "可执行", "deb": "可执行",
}
# 默认兜底分类
default_category = "其他"
步骤 2:编写整理逻辑
完整可执行脚本 organizer.py:
#!/usr/bin/env python3
"""桌面文件自动整理工具"""
import os
import shutil
import logging
from pathlib import path
# 配置日志
logging.basicconfig(
filename="organize_log.json",
level=logging.info,
format="%(asctime)s | %(message)s"
)
category_map = {
"pdf": "文档", "doc": "文档", "docx": "文档", "txt": "文档", "md": "文档",
"jpg": "图片", "jpeg": "图片", "png": "图片", "gif": "图片",
"mp4": "视频", "mov": "视频", "mp3": "音频", "wav": "音频",
"zip": "压缩包", "rar": "压缩包", "7z": "压缩包",
"py": "代码", "js": "代码", "html": "代码",
}
default_category = "其他"
def get_category(filename: str) -> str:
"""根据文件名返回分类文件夹名"""
ext = path(filename).suffix.lower().lstrip(".")
return category_map.get(ext, default_category)
def move_file(src: path, dest_dir: path) -> path:
"""移动文件,同名时自动加 _1, _2 后缀"""
dest_dir.mkdir(parents=true, exist_ok=true)
dest = dest_dir / src.name
if dest.exists():
stem, suffix = src.stem, src.suffix
counter = 1
while dest.exists():
dest = dest_dir / f"{stem}_{counter}{suffix}"
counter += 1
shutil.move(str(src), str(dest))
logging.info(f"移动: {src.name} -> {dest}")
return dest
def organize(target_dir: str = none):
"""扫描并整理目标目录"""
if target_dir is none:
target_dir = os.path.expanduser("~/desktop")
root = path(target_dir).resolve()
if not root.exists():
print(f"❌ 目录不存在: {root}")
return
count = 0
for item in root.iterdir():
if not item.is_file():
continue
if item.name.startswith("."): # 跳过隐藏文件
continue
category = get_category(item.name)
dest_dir = root / category
move_file(item, dest_dir)
count += 1
print(f"✅ 完成,共整理 {count} 个文件")
logging.info(f"=== 本次整理 {count} 个文件 ===")
if __name__ == "__main__":
organize()
步骤 3:运行脚本
# 整理桌面(默认) python3 organizer.py # 整理指定目录 python3 organizer.py -- /path/to/messy/folder
运行后桌面会变成这样的结构:
desktop/
├── 文档/
│ ├── 简历.pdf
│ └── 笔记.md
├── 图片/
│ ├── 截图.png
│ └── 头像.jpg
├── 压缩包/
│ └── 素材包.zip
├── 代码/
│ └── app.js
└── 其他/
└── readme步骤 4:表格对比 — 整理前后效果
| 维度 | 整理前 | 整理后 |
|---|---|---|
| 文件位置 | 全部混在桌面根目录 | 按类型分到子文件夹 |
| 查找速度 | 肉眼翻找,30 秒+ | 直接进对应文件夹 |
| 文件数量(示例) | 47 个文件平铺 | 5 个文件夹各装 1-20 个 |
| 重复文件风险 | 手动改名容易出错 | 脚本自动追加 _1, _2 后缀 |
| 可追溯性 | 无记录 | organize_log.json 记录每次操作 |
步骤 5:进阶 — 添加定时自动整理
方案 a:linux / macos 用 cron
# 每周一、四早上 9 点自动整理 0 9 * * 1,4 cd ~/desktop-organizer && python3 organizer.py
方案 b:windows 用任务计划程序
- 打开"任务计划程序"
- 创建基本任务,名称填"桌面整理"
- 触发器选择"每周",指定周一和周四
- 操作选择"启动程序",程序填
python.exe,参数填organizer.py的绝对路径
方案 c:脚本内加防重复标记
marker_file = path.home() / ".desktop_organize_done"
def should_run() -> bool:
"""避免同一天重复整理"""
if marker_file.exists():
last_run = marker_file.stat().st_mtime
if (time.time() - last_run) < 86400: # 24 小时内
return false
return true
总结
今天用 60 行 python 代码实现了一个桌面文件自动整理器,核心收获:
pathlib.path** 比os.path更直观** —item.is_file()、item.suffix写起来更清晰- 同名处理是实战必须考虑的细节 — 加后缀
_1的逻辑虽然简单,但能避免真实场景中的数据丢失 - 日志记录是脚本工程的标配 — 有了日志,出问题能快速定位,也能做统计
这个脚本可以按自己需求扩展:比如加入"移动前先备份到 trash 目录"、“按创建时间分月归档”、“整合到 hermes 定时任务里每天自动跑”。
以上就是使用python写一个桌面文件自动整理工具的详细内容,更多关于python桌面文件整理工具的资料请关注代码网其它相关文章!
发表评论