You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本重命名视频文件时丢失扩展名问题咨询

解决视频重命名丢失扩展名的问题

问题原因

你的脚本丢失扩展名的核心原因是:构造新文件名时完全没有保留原文件的扩展名,只拼接了电影名称、年份和类型。此外脚本还有两个逻辑漏洞:

  • 正则提取名称时未考虑扩展名,但更关键的是没将扩展名加入新文件名
  • os.rename 语句缩进错误,无论是否成功获取电影类型都会执行,极端情况下会因new_name未定义抛出异常

修复方案

  1. 拆分文件名与扩展名:用os.path.splitext()替代纯正则,更可靠地分离文件名主体和扩展名
  2. 保留扩展名到新文件名:构造新名称时把原扩展名追加到末尾
  3. 修正重命名逻辑的缩进:确保只有在成功生成合法新名称后才执行重命名

修复后的完整代码

import os
import re
import requests

# 替换为你的TMDb API密钥
api_key = 'My Api KEY'

def get_movie_id(name, year):
    name_encoded = requests.utils.quote(name)
    url = f'https://api.themoviedb.org/3/search/movie?api_key={api_key}&query={name_encoded}&year={year}'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if data['total_results'] > 0:
            movie = data['results'][0]
            return movie['id']
    return None

def get_movie_genre(movie_id):
    url = f'https://api.themoviedb.org/3/movie/{movie_id}?api_key={api_key}'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if data['genres']:
            return data['genres'][0]['name']
    return None

# 遍历目录下的文件
for file in os.listdir():
    # 支持更多视频格式,可自行添加
    if file.endswith(('.avi', '.mp4', '.mkv')):
        # 拆分文件名和扩展名
        file_base, file_ext = os.path.splitext(file)
        # 从文件名主体中提取名称和年份
        match = re.search(r'(.*) \(((?:19|20)\d\d)\)', file_base)
        if not match:
            print(f"无法解析文件名:{file}")
            continue
        
        name = match.group(1)
        year = match.group(2)
        
        movie_id = get_movie_id(name, year)
        if not movie_id:
            print(f"未找到电影:{name} ({year})")
            continue
        
        genre = get_movie_genre(movie_id)
        if not genre:
            print(f"无法获取电影类型:{name} ({year})")
            continue
        
        # 构造带扩展名的新文件名
        new_name = f'{name} ({year}) [{genre}]{file_ext}'
        
        if not os.path.exists(new_name):
            print(f'{file} -> {new_name}')
            os.rename(file, new_name)
        else:
            print(f"文件已存在,跳过:{new_name}")

额外优化点

  • 增加了对.mkv格式的支持
  • 增加了异常情况的处理(无法解析文件名、找不到电影、获取不到类型)
  • 检查新文件是否存在时也包含扩展名,避免误判
  • 只有在所有步骤都成功时才执行重命名,避免无效操作

内容的提问来源于stack exchange,提问作者user3520363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:50:29