【AI技术_工具_资讯】用 Python + AI 构建智能文件分类整理工具

📅 2026/7/14 0:57:41
【AI技术_工具_资讯】用 Python + AI 构建智能文件分类整理工具
前言你的桌面是不是堆满了各种文件截图、PDF、Markdown、CSV、各种命名乱七八遭的文件……每次找文件都要翻半天。手动整理又无聊又耗时。这篇博客教你用 Python 调用 AI 模型自动识别文件内容语义把文件归类到对应文件夹。全程无需手动干预一个脚本跑完桌面清清爽爽。主题介绍传统文件整理方案通常是基于文件扩展名或文件名关键词做规则匹配——但这种方法很脆弱notes.pdf和contract.pdf都是 PDF应该放不同文件夹IMG_2026.jpg和photo_backup.jpg文件名毫无语义新建的格式比如.env、.yaml规则库得跟着更新AI 语义分类方案的思路读取文件内容文本类或文件名路径二进制类让大模型判断这个文件应该放在哪个类别然后把文件移过去。核心优势✅ 理解文件真实内容语义不是死板规则✅ 零配置启动AI 自动学习你的文件类型✅ 可解释每次分类结果都可追溯✅ 一次编写持续受益环境准备依赖安装pipinstallopenai只要openai这个库支持任何 OpenAI API 兼容的模型Claude、Gemini、本地模型都行。配置文件在项目目录创建.env# 支持任意 OpenAI API 兼容模型exportOPENAI_API_KEYsk-xxxexportOPENAI_API_BASEhttps://api.openai.com/v1exportAI_MODELclaude-sonnet-4-20250514实操步骤步骤1定义文件分类策略首先我们定义一个类别映射。类别用自然语言描述AI 会根据文件内容自动匹配# categorize.pyCATEGORIES{documents:正式文档、报告、合同、简历、简历等,code:源代码文件、脚本、配置文件.py, .js, .ts, .json, .yaml, .toml,notes:学习笔记、日记、备忘、草稿,data:数据文件.csv, .xlsx, .sqlite, .parquet,media:图片、视频、音频等媒体文件,downloads:临时下载、安装包、压缩包,finance:发票、账单、报销、财务相关,trash:不确定或应该丢弃的文件}步骤2编写文件内容读取器不同类型文件读取方式不同我们做个适配器# reader.pyimportmimetypesfrompathlibimportPathdefread_file_content(file_path:Path,max_bytes:int8000)-str|None:读取文件内容返回文本或 None二进制文件跳过try:extfile_path.suffix.lower()# 文本类文件直接读取text_exts{.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml,.html,.css,.py,.js,.ts,.java,.go,.rs,.sh,.sql,.ini,.cfg}ifextintext_exts:returnfile_path.read_text(encodingutf-8,errorsignore)[:max_bytes]# PDF 文件需要 pdfplumber可选ifext.pdf:try:importpdfplumberwithpdfplumber.open(str(file_path))aspdf:return\n.join(page.extract_text()orforpageinpdf.pages[:2])[:max_bytes]exceptImportError:returnNone# 二进制文件图片、视频、压缩包等返回 NonereturnNoneexceptExceptionase:print(f ⚠️ 读取失败{file_path.name}:{e})returnNone步骤3编写 AI 分类器这是核心——调用大模型做语义分类# classifier.pyimportjsonfromopenaiimportOpenAIfrompathlibimportPath clientOpenAI()defclassify_file(file_name:str,file_content:str|None,categories:dict)-str: 调用 AI 模型对文件进行分类 参数 file_name: 文件名含扩展名 file_content: 文件文本内容可能为 None categories: 可用类别字典 {category_name: description} 返回 匹配到的类别名称 # 构建类别选项只给类别名和简短描述category_options\n.join(f{i1}. **{name}** —{desc}fori,(name,desc)inenumerate(categories.items()))# 构建提示词content_previewfile_contentiffile_contentelse二进制文件无法读取内容ifcontent_previewandlen(content_preview)2000:content_previewcontent_preview[:2000]\n...已截断promptf你是一个文件整理助手。请根据文件信息判断它最适合归入以下哪个类别 文件名{file_name}文件内容预览{content_preview}可选类别 {category_options} 请只输出类别编号不要输出其他内容。 response client.chat.completions.create( modelPath.home() / .env # 实际项目中用 config 读取 modelclaude-sonnet-4-20250514, messages[ {role: system, content: 你是一个精准的文件分类助手请只输出类别编号数字。}, {role: user, content: prompt}, ], temperature0, max_tokens5, ) # 解析输出只取第一个数字 result response.choices[0].message.content.strip() for i, cat in enumerate(categories.keys()): if str(i 1) result: return cat return trash # 兜底 省钱技巧max_tokens5把输出压到最小temperature0保证确定性。单次分类成本约 0.005 元1000 个文件才 5 块钱。步骤4编写文件移动执行器分类完成后把文件安全移动到目标文件夹# organizer.pyfrompathlibimportPathfromdatetimeimportdatetimeimportshutildeforganize_files(source_dir:str,categories:dict,dry_run:boolTrue)-list[dict]: 遍历源目录对每个文件进行分类并移动 参数 source_dir: 待整理目录路径 categories: 类别配置 dry_run: True只预览不执行False实际移动 返回 分类记录列表 [{file_name, category, source_path, target_path}] srcPath(source_dir)records[]forfile_pathinsrc.iterdir():ifnotfile_path.is_file()orfile_path.name.startswith(.):continue# 读取内容contentread_file_content(file_path)# AI 分类categoryclassify_file(file_path.name,content,categories)target_dirsrc/categoryifdry_run:print(f {file_path.name}→{category}/)records.append({file:file_path.name,category:category,target:str(target_dir/file_path.name)})continue# 实际移动target_dir.mkdir(parentsTrue,exist_okTrue)target_pathtarget_dir/file_path.name# 处理重名文件counter1whiletarget_path.exists():target_pathtarget_dir/f{file_path.stem}_{counter}{file_path.suffix}counter1shutil.move(str(file_path),str(target_path))print(f ✅{file_path.name}→{category}/)records.append({file:file_path.name,category:category,target:str(target_path)})returnrecords步骤5整合为主入口脚本# main.pyimportosfromdotenvimportload_dotenvfromorganizerimportorganize_files,CATEGORIESdefmain():load_dotenv()# 要整理的目录target_diros.getenv(ORGANIZE_DIR,./Downloads)print(f 开始扫描目录:{target_dir})print(f 可用类别:{, .join(CATEGORIES.keys())})print(-*40)# 先预览recordsorganize_files(target_dir,CATEGORIES,dry_runTrue)print(-*40)print(f 预览结果:{len(records)}个文件)# 确认执行ifinput(\n确认执行移动(y/n): ).strip().lower()y:print(\n⚡ 开始移动文件...)organize_files(target_dir,CATEGORIES,dry_runFalse)print( 整理完成)if__name____main__:main()步骤6运行并验证exportORGANIZE_DIR./Desktoppython main.py输出示例 开始扫描目录: ./Desktop 可用类别: documents, code, notes, data, media, downloads, finance, trash ──────────────────────────────────────── resume_final_v3.pdf → documents/ screenshot_20260712.png → media/ notes_july.md → notes/ api_keys.json → code/ expense_report.xlsx → finance/ ──────────────────────────────────────── 预览结果: 5 个文件 确认执行移动(y/n): y ⚡ 开始移动文件... ✅ resume_final_v3.pdf → documents/ ✅ screenshot_20260712.png → media/ ✅ notes_july.md → notes/ ✅ api_keys.json → code/ ✅ expense_report.xlsx → finance/ 整理完成扩展思路定时自动运行用 cron 每周自动扫描 Downloads 目录02* *0cd/path/to/projectpython main.py--autoorganize.log21增量模式只处理昨天及之后创建的文件避免重复分类自定义类别在CATEGORIES中按需添加你的文件类型日志记录每次分类结果写入 SQLite方便日后回查和纠正总结这个工具的核心价值在于把文件该放哪这个判断交给 AI而不是写死规则。文本文件靠内容语义分类准确率远超关键词匹配二进制文件靠文件名上下文判断覆盖大多数场景总成本极低1000 文件约 5 元每周跑一次几乎免费代码约 150 行可复用、可扩展下次看到桌面堆成山直接跑这个脚本一分钟内整理完毕。 提示首次运行时务必先用dry_runTrue预览确认分类结果满意后再正式执行。