Python 自动化之批量重命名与智能文件分类

📅 2026/7/13 22:15:53
Python 自动化之批量重命名与智能文件分类
电脑用久了桌面和下载文件夹总会变得一团糟。用 Python 写几个脚本一键重命名、按类型归档、清理重复文件。一、批量重命名1. 统一命名规则importosdefbatch_rename(directory,prefixfile,start1,digits3): 统一命名prefix_001.ext, prefix_002.ext ... directory: 文件夹路径 prefix: 文件名前缀 start: 起始编号 digits: 编号位数 files[fforfinos.listdir(directory)ifos.path.isfile(os.path.join(directory,f))]# 按修改时间排序files.sort(keylambdax:os.path.getmtime(os.path.join(directory,x)))fori,filenameinenumerate(files):name,extos.path.splitext(filename)new_namef{prefix}_{str(starti).zfill(digits)}{ext}old_pathos.path.join(directory,filename)new_pathos.path.join(directory,new_name)os.rename(old_path,new_path)print(f{filename}→{new_name})2. 替换文件名中的关键词defreplace_text(directory,old_text,new_text):批量替换文件名中的关键词count0forfinos.listdir(directory):fpos.path.join(directory,f)ifos.path.isfile(fp)andold_textinf:new_namef.replace(old_text,new_text)os.rename(fp,os.path.join(directory,new_name))count1print(f共替换{count}个文件)二、智能文件归档importshutil EXTENSION_MAP{.jpg:图片,.jpeg:图片,.png:图片,.gif:图片,.doc:文档,.docx:文档,.pdf:文档,.txt:文档,.xls:表格,.xlsx:表格,.zip:压缩包,.rar:压缩包,.7z:压缩包,.mp4:视频,.avi:视频,.mp3:音乐,.wav:音乐,.py:代码,.java:代码,.js:代码,.html:代码,}defauto_sort(directory):按文件类型自动归档forfinos.listdir(directory):fpos.path.join(directory,f)ifnotos.path.isfile(fp):continue_,extos.path.splitext(f)folderEXTENSION_MAP.get(ext.lower(),其他)targetos.path.join(directory,folder)os.makedirs(target,exist_okTrue)shutil.move(fp,os.path.join(target,f)) 觉得有用的话点赞 关注【张老师技术栈】吧