佛山网站制作公司,最吉利旺财的公司名字,厦门网站建设哪家专业,网站没有收录用 Python 写一个自动整理文件的脚本很简单#xff0c;核心思路是#xff1a;按文件后缀#xff08;如 .jpg、.pdf#xff09;将文件分类#xff0c;移动到对应的文件夹#xff08;如「图片」「文档」#xff09;中。以下是一个实用的实现方案#xff0c;新手也能轻松修…
用 Python 写一个自动整理文件的脚本很简单核心思路是按文件后缀如 .jpg、.pdf将文件分类移动到对应的文件夹如「图片」「文档」中。以下是一个实用的实现方案新手也能轻松修改和使用。
脚本功能
将指定文件夹比如「下载」文件夹中的所有文件按类型自动分类到子文件夹中例如
图片.jpg, .png, .gif 等→ 图片/文档.pdf, .docx, .xlsx 等→ 文档/视频.mp4, .avi 等→ 视频/其他未定义类型 → 其他文件/
实现代码
import os
import shutildef 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 catbreak# 创建对应的类别文件夹如果不存在category_dir os.path.join(target_dir, category)os.makedirs(category_dir, exist_okTrue)# 处理同名文件避免覆盖target_path os.path.join(category_dir, item)counter 1while os.path.exists(target_path):# 例如test.jpg → test(1).jpgname, 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示例rC:\Users\你的用户名\Downloads# Mac/Linux示例/Users/你的用户名/Downloadstarget_directory rC:\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 路径格式rC:\Users\你的用户名\Downloads注意前面的 r 不能少Mac/Linux 路径格式/Users/你的用户名/Downloads运行脚本保存为 file_organizer.py在终端执行 python file_organizer.py。自定义扩展
添加更多类型在 file_categories 字典中添加新的类别和对应的后缀例如
电子书: [.epub, .mobi]修改文件夹名称直接修改字典的键如将「图片」改为「Images」。排除特定文件如果有不想移动的文件如 README.txt可在遍历前添加判断跳过。
注意事项
首次使用建议先备份文件避免误操作。脚本会跳过已存在的分类文件夹如已有的「图片」文件夹不会递归处理子文件夹。遇到同名文件时会自动在文件名后加编号如 test(1).jpg避免覆盖。
用这个脚本从此告别杂乱的下载文件夹啦