
用 Python 写一个自动整理文件的脚本很简单,核心思路是:按文件后缀(如 .jpg
、.pdf
)将文件分类,移动到对应的文件夹(如「图片」「文档」)中。以下是一个实用的实现方案,新手也能轻松修改和使用。
脚本功能
将指定文件夹(比如「下载」文件夹)中的所有文件,按类型自动分类到子文件夹中,例如:
- 图片(.jpg, .png, .gif 等)→
图片/
- 文档(.pdf, .docx, .xlsx 等)→
文档/
- 视频(.mp4, .avi 等)→
视频/
- 其他未定义类型 →
其他文件/
实现代码
python
import os
import shutil
def organize_files(target_dir):
# 定义文件类型与对应文件夹的映射(可根据需求扩展)
file_categories = {
'图片': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp'],
'文档': ['.pdf', '.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.txt', '.md'],
'视频': ['.mp4', '.avi', '.mov', '.mkv', '.flv'],
'音频': ['.mp3', '.wav', '.flac', '.m4a'],
'压缩包': ['.zip', '.rar', '.7z', '.tar', '.gz'],
'程序': ['.exe', '.msi', '.py', '.java', '.cpp', '.html', '.css', '.js']
}
# 遍历目标文件夹中的所有项目
for item in os.listdir(target_dir):
item_path = os.path.join(target_dir, item)
# 跳过文件夹(只处理文件)
if os.path.isdir(item_path):
continue
# 获取文件后缀(转为小写,避免大小写问题)
file_ext = os.path.splitext(item)[1].lower()
# 确定文件所属类别
category = '其他文件' # 默认类别
for cat, exts in file_categories.items():
if file_ext in exts:
category = cat
break
# 创建对应的类别文件夹(如果不存在)
category_dir = os.path.join(target_dir, category)
os.makedirs(category_dir, exist_ok=True)
# 处理同名文件(避免覆盖)
target_path = os.path.join(category_dir, item)
counter = 1
while os.path.exists(target_path):
# 例如:test.jpg → test(1).jpg
name, ext = os.path.splitext(item)
target_path = os.path.join(category_dir, f"{name}({counter}){ext}")
counter += 1
# 移动文件到目标文件夹
shutil.move(item_path, target_path)
print(f"已移动:{item} → {category}/")
if __name__ == "__main__":
# 替换为你要整理的文件夹路径(注意斜杠方向)
# Windows示例:r"C:\Users\你的用户名\Downloads"
# Mac/Linux示例:"/Users/你的用户名/Downloads"
target_directory = r"C:\Users\你的用户名\Downloads"
# 检查路径是否存在
if not os.path.exists(target_directory):
print(f"错误:路径不存在 → {target_directory}")
else:
print(f"开始整理文件夹:{target_directory}")
organize_files(target_directory)
print("整理完成!")
使用方法
-
修改路径 :将代码中
target_directory
的值改为你要整理的文件夹路径(比如下载文件夹)。- Windows 路径格式:
r"C:\Users\你的用户名\Downloads"
(注意前面的r
不能少) - Mac/Linux 路径格式:
"/Users/你的用户名/Downloads"
- Windows 路径格式:
-
运行脚本 :保存为
file_organizer.py
,在终端执行python file_organizer.py
。
自定义扩展
- 添加更多类型 :在
file_categories
字典中添加新的类别和对应的后缀,例如:
'电子书': ['.epub', '.mobi']
- 修改文件夹名称:直接修改字典的键(如将「图片」改为「Images」)。
- 排除特定文件 :如果有不想移动的文件(如
README.txt
),可在遍历前添加判断跳过。
注意事项
- 首次使用建议先备份文件,避免误操作。
- 脚本会跳过已存在的分类文件夹(如已有的「图片」文件夹),不会递归处理子文件夹。
- 遇到同名文件时,会自动在文件名后加编号(如
test(1).jpg
),避免覆盖。
用这个脚本,从此告别杂乱的下载文件夹啦!