Python 代码:批量重命名视频文件,删除文件名中的数字

该代码实现的功能是:在 Python 代码执行成功后,对 output_dir 目录下的视频文件进行重新命名,删除文件名中第一个英文字母之前的所有数字,并将其转换为大写字母。

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)

# 对 output_dir 目录下的视频文件进行重新命名
for file in os.listdir(output_dir):
    if os.path.splitext(file)[1] == '.mp4':
        old_name = os.path.join(output_dir, file)
        new_name = os.path.join(output_dir, os.path.splitext(file)[0].replace(os.path.splitext(file)[0][0], '', 1).upper() + '.mp4')
        os.rename(old_name, new_name)

代码说明:

  1. 导入库

    • os: 用于操作文件和目录
    • glob: 用于查找符合特定模式的文件
    • natsort: 用于自然排序文件列表
  2. 获取所有 mp4 文件路径

    • dir_path: 指定视频文件所在的目录
    • output_dir: 指定输出目录
    • 使用 os.walk 遍历目录,并获取所有 mp4 文件的路径
    • 使用 natsorted 对文件列表进行自然排序
  3. 生成 ffmpeg 命令

    • 将每个 mp4 文件转换为 ts 文件
    • 使用 os.path.splitext 分割文件名和扩展名
    • 使用 f-string 格式化 ffmpeg 命令
  4. 合并 ts 文件

    • 使用 os.path.basename 获取文件名
    • 使用 os.path.dirname 获取文件所在的目录
    • 使用 os.path.join 拼接文件路径
    • 使用 os.path.splitext 分割文件名和扩展名
    • 使用 f-string 格式化 ffmpeg 命令
  5. 执行 ffmpeg 命令

    • 使用 os.system 执行 ffmpeg 命令
  6. 删除 ts 文件

    • 使用 glob.glob 查找所有 ts 文件
    • 使用 os.remove 删除 ts 文件
  7. 重命名文件

    • 使用 os.listdir 获取输出目录下的所有文件
    • 使用 os.path.splitext 分割文件名和扩展名
    • 使用 os.path.join 拼接文件路径
    • 使用 os.rename 重命名文件

注意:

  • 代码中 dir_pathoutput_dir 需要根据实际情况修改
  • 需要安装 ffmpeg,并将其添加到系统环境变量中
  • 该代码仅供参考,需要根据实际情况进行调整

相关链接:

Python 代码:批量重命名视频文件,删除文件名中的数字

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

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