**写了个自动整理下载视频的脚本:按片名归档、自动重命名、生成目录索引

视频下载多了以后,管理成了大问题。下载器输出的文件名五花八门,有的是哈希值,有的是"videoplayback",有的是带一堆参数的长串。手动改名归类太费时间,写了个Python脚本自动搞定。

痛点

下载100部纪录片后文件夹是这样的:

downloads/

├── 8a7f3c2e1b.mp4

├── VIDE_20260715_193021.mp4

├── 航拍中国第3季第5集_高清版(1).mp4

├── 航拍中国第三季05_1080P.mp4

├── index.m3u8.bak.mp4

└── (还有94个乱七八糟的文件)

问题:命名不统一、同片不同名、无法按片名归类、无法按集数排序。

脚本功能设计

识别文件真实片名(从文件名提取+模糊匹配)

统一重命名为 片名_SxxExx_清晰度.mp4 格式

自动创建分类文件夹并归档

生成目录索引HTML

完整实现

python

import os

import re

import shutil

from pathlib import Path

class VideoOrganizer:

def init (self, download_dir, output_dir):

self.download_dir = Path(download_dir)

self.output_dir = Path(output_dir)

复制代码
    # 分类关键词表
    self.categories = {
        "自然地理": ["航拍中国", "美丽中国", "自然的力量", "第三极", "森林"],
        "历史文化": ["国家宝藏", "国宝", "故宫", "敦煌", "历史", "考古"],
        "美食生活": ["舌尖", "风味人间", "味道", "美食"],
        "科技工程": ["大国重器", "超级工程", "创新中国", "科技"],
    }

def parse_filename(self, filename: str) -> dict:
    """从文件名提取片名、季数、集数、清晰度"""
    name = Path(filename).stem
    
    # 提取片名(匹配已知片名词典或最长中文字符串)
    title_match = re.search(r'[\u4e00-\u9fa5]{2,}', name)
    title = title_match.group() if title_match else "未分类"
    
    # 规范化片名(处理"第3季"和"第三季")
    cn_num = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5}
    season = re.search(r'第([0-9一二三四五])季', title)
    episode = re.search(r'第(\d{1,2})集|E(\d{1,2})', name)
    quality = re.search(r'(4K|1080P|720P|高清|超清|标清)', name)
    
    return {
        "title": re.sub(r'第[0-9一二三四五]季', '', title).strip(),
        "season": int(cn_num.get(season.group(1), season.group(1))) if season else 1,
        "episode": int(episode.group(1) or episode.group(2)) if episode else 0,
        "quality": quality.group() if quality else "高清"
    }

def new_filename(self, info: dict) -> str:
    """生成规范文件名"""
    return (f"{info['title']}_"
            f"S{info['season']:02d}E{info['episode']:02d}_"
            f"{info['quality']}.mp4")

def get_category(self, title: str) -> str:
    """按关键词归类"""
    for category, keywords in self.categories.items():
        if any(kw in title for kw in keywords):
            return category
    return "其他"

def organize(self):
    """执行整理"""
    moved = 0
    for file in self.download_dir.glob("*.mp4"):
        info = self.parse_filename(file.name)
        category = self.get_category(info["title"])
        
        # 创建目录:输出/分类/片名
        target_dir = self.output_dir / category / info["title"]
        target_dir.mkdir(parents=True, exist_ok=True)
        
        # 移动并重命名
        target = target_dir / self.new_filename(info)
        shutil.move(str(file), str(target))
        moved += 1
        print(f"[{category}] {file.name} -> {target}")
    
    print(f"\n完成:共整理 {moved} 个文件")

def generate_index(self):
    """生成HTML目录索引"""
    html = ["<html><head><meta charset='utf-8'>",
            "<title>纪录片库目录</title></head><body>",
            "<h1>私人纪录片库</h1>"]
    
    for category_dir in sorted(self.output_dir.iterdir()):
        if not category_dir.is_dir():
            continue
        html.append(f"<h2>{category_dir.name}</h2><ul>")
        for title_dir in sorted(category_dir.iterdir()):
            count = len(list(title_dir.glob("*.mp4")))
            html.append(f"<li>{title_dir.name} ({count}集)</li>")
        html.append("</ul>")
    
    html.append("</body></html>")
    
    index_file = self.output_dir / "index.html"
    index_file.write_text("".join(html), encoding="utf-8")
    print(f"索引已生成: {index_file}")

if name == "main ":

org = VideoOrganizer(

download_dir=r"D:\downloads",

output_dir=r"D:\纪录片库"

)

org.organize()

org.generate_index()

整理后的效果

纪录片库/

├── index.html

├── 自然地理/

│ ├── 航拍中国/

│ │ ├── 航拍中国_S03E01_1080P.mp4

│ │ ├── 航拍中国_S03E02_1080P.mp4

│ │ └── ...

│ └── 美丽中国/

├── 历史文化/

│ ├── 国家宝藏/

│ └── 如果国宝会说话/

├── 美食生活/

│ └── 舌尖上的中国/

└── 科技工程/

└── 大国重器/

踩过的坑

同名不同写:「航拍中国第三季」和「航拍中国第3季」会被识别成两个片名,需要先做中文数字归一化。

集数格式混乱:「第5集」「05」「E5」「EP05」四种写法都存在,正则要覆盖全。

临时文件干扰:下载器会留下 .tmp、.bak 等临时文件,整理前要先过滤 *.mp4 后缀。

移动 vs 复制:跨盘移动(C盘到D盘)实际是复制+删除,大文件很慢。如果需要保留原文件,把 shutil.move 换成 shutil.copy2。

扩展思路

接入视频MD5去重,识别重复下载

用ffprobe读取视频实际时长,补充到索引里

生成JSON格式的媒体库元数据,配合Jellyfin/Emby做家庭影院

总结

下载用VideoToolboxCS(盘资源基地cc.ewp.cc可找到),整理用这个脚本,一套流程下来几百个视频十分钟归档完毕。代码不到200行,有同样需求的可以直接拿去改。

https://pan.baidu.com/s/1zWj28SK28yFfBckjjHBxIw?pwd=fqqg 提取码:fqqg

相关推荐
“AI国潮设计-小江”8 小时前
【AIGC实战】Python+SDXL批量生成“潮汕英歌舞不倒翁”IP | 角色一致性与多场景融合方案,附完整代码
开发语言·人工智能·python·prompt·aigc
传奇开心果编程8 小时前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
Linux_cy8 小时前
服务器管理工具哪个好用?我用了七八个
运维·服务器·javascript·python·ssh·面板·gmssh
MoRanzhi12038 小时前
第6篇(下)· 使用 PyQt5 实现 2048 高性能计算版:统一运行控制与跨模式安全交接
python·pyqt·进程管理·状态机·软件架构·并发控制·数据一致性
code tsunami9 小时前
【无标题】
开发语言·python
CodeGL9 小时前
10、Python基础之进程和线程
开发语言·python
AI视频工具指南10 小时前
怎么用 AI 做悬疑短剧?
人工智能·aigc·音视频
TechWayfarer10 小时前
PHP漏洞被利用,怎么揪出攻击IP?
开发语言·python·tcp/ip·网络安全·php
2601_9679801111 小时前
Python列表操作方法详解
python·数据类型·修改·列表操作·功能汇总
卡卡~~11 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法