import os
import glob
from natsort import natsorted

# 当前文件夹下的所有 mp4 路径
L = []
dir_path = r'E:\home\up'
output_dir = r'E:\home\up\1'
for root, dirs, files in os.walk(dir_path):
    files = natsorted(files)
    for file in files:
        if os.path.splitext(file)[1] == '.mp4':
            file_path = os.path.join(root, file)
            L.append(file_path)

# 生成 ffmpeg 命令
commands = []
for l in L:
    ts_file = os.path.join(
        os.path.dirname(l), os.path.splitext(os.path.basename(l))[0] + '.ts')
    commands.append(
        f'ffmpeg -i '{l}' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb '{ts_file}'')

concat_command = (
    f'ffmpeg -i 'concat:{{'|''.join([os.path.join(os.path.dirname(l), os.path.splitext(os.path.basename(l))[0] + '.ts') for l in L])}}' '
    '-acodec copy -vcodec copy -bsf:a aac_adtstoasc '
    f''{os.path.join(output_dir, os.path.splitext(os.path.basename(L[0]).replace('00', '-', 1))[0][:-1].upper() + '.mp4')}''
)

# 执行 ffmpeg 命令
for command in commands:
    os.system(command)

os.system(concat_command)

# 删除 ts 文件
for ts_file in glob.glob(os.path.join(dir_path, '*.ts')):
    os.remove(ts_file)

# 重命名文件
for file in os.listdir(output_dir):
    if os.path.splitext(file)[1] == '.mp4':
        file_path = os.path.join(output_dir, file)
        new_file_name = os.path.splitext(file)[0].split('_', 1)[-1] + '.mp4'
        new_file_path = os.path.join(output_dir, new_file_name)
        os.rename(file_path, new_file_path)

代码说明:

  1. 导入必要的库:os 用于文件操作,glob 用于匹配文件,natsort 用于自然排序文件名。
  2. 获取当前文件夹下的所有 MP4 文件路径,并使用 natsort 排序。
  3. 生成 ffmpeg 命令,将每个 MP4 文件转换为 TS 格式。
  4. 生成 ffmpeg 命令,将所有 TS 文件合并成一个新的 MP4 文件,并将文件名修改为去掉前缀数字后的内容。
  5. 执行 ffmpeg 命令。
  6. 删除所有生成的 TS 文件。
  7. 遍历输出文件夹,对所有 MP4 文件进行重命名,删除文件名中第一个英文前的所有数字。

注意:

  • 代码中的 dir_pathoutput_dir 需要根据实际路径进行修改。
  • 代码中的 replace('00', '-', 1) 用于将文件名中的 '00' 替换为 '-',并只替换一次。
  • 代码中的 [:-1].upper() 用于将文件名去掉最后一个字符并转换为大写。
  • 代码中的 split('_', 1)[-1] 用于将文件名按照 '_' 分割,并取最后一个元素。

使用方法:

  1. 将代码保存为 .py 文件。
  2. 修改代码中的 dir_pathoutput_dir 为实际路径。
  3. 运行代码。

示例:

假设当前文件夹下存在以下 MP4 文件:

01_test.mp4
02_test.mp4
03_test.mp4

运行代码后,输出文件夹下将生成以下 MP4 文件:

TEST.mp4

所有 MP4 文件名中的前缀数字都被删除了。

希望这个代码能够帮助到您!

Python 代码:批量重命名 MP4 文件,删除文件名中的前缀数字

原文地址: https://www.cveoy.top/t/topic/nCeK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录