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

视频下载多了以后,管理成了大问题。下载器输出的文件名五花八门,有的是哈希值,有的是"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

相关推荐
xys_6781 小时前
深挖C语言:动态内存管理
c语言·开发语言
码云数智-园园1 小时前
Python如何将律师的Excel噩梦变成自动化系统
python·自动化·excel
belldeep1 小时前
python:Selenium 4.47 编码新的写法
python·selenium
卷无止境1 小时前
除了开发api,FastAPI其实也可以配合jinja2模板写页面
后端·python·fastapi
OPEN-F1 小时前
Python进阶教程:项目工程化与虚拟环境
开发语言·python
吴声子夜歌1 小时前
Java面试——基础
java·开发语言·面试
OPEN-F2 小时前
Python进阶教程:自动化办公实战
python·c#·自动化
minglie12 小时前
python串口的stream数据mock
python
晚风醉蝶2 小时前
1-16-计数排序-CountingSort
python·算法·排序算法