该 Python 脚本用于修改输出文件名规则,并针对 'h_' 前缀的文件进行了特殊处理。

修改后的代码如下:

import os
import glob
from natsort import natsorted

dir_path = r'E:\home\up'
output_dir = r'E:\home\up\1'

# 当前文件夹下的所有 mp4 路径
L = []
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:
    if os.path.basename(l).startswith('h_'):
        new_file_name = os.path.basename(l)[2:]
    else:
        new_file_name = os.path.basename(l)[1:]
    ts_file = os.path.join(os.path.dirname(l), new_file_name + '.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.basename(l)[2:] if os.path.basename(l).startswith('h_') else os.path.basename(l)[1:])) + '.ts' for l in L])}}" '
    '-acodec copy -vcodec copy -bsf:a aac_adtstoasc '
    f"'{os.path.join(output_dir, (os.path.basename(L[0])[2:] if os.path.basename(L[0]).startswith('h_') else os.path.basename(L[0])) + '.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 mp4_file in glob.glob(os.path.join(output_dir, '*.mp4')):
    file_name = os.path.basename(mp4_file)
    new_file_name = file_name[file_name.find(file_name.lstrip('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')[0]):]
    os.rename(mp4_file, os.path.join(output_dir, new_file_name))

主要修改点:

  1. 文件名截取规则: 从第一个英文字母开始截取,如果文件名是以 'h_' 开头的则从第二个英文字母开始截取。
  2. 取消删除数字前缀功能: 代码中已删除相关的代码片段。

代码说明:

  • 脚本使用 natsorted 库对文件进行自然排序,确保文件按顺序处理。
  • 脚本使用 os.path.basename 获取文件名,并使用 os.path.dirname 获取文件路径。
  • 脚本使用 ffmpeg 命令将 mp4 文件转换为 ts 文件,并将所有 ts 文件合并成一个新的 mp4 文件。
  • 脚本最后删除所有生成的 ts 文件。

注意事项:

  • 请确保 ffmpeg 已安装并配置好环境变量。
  • 代码中的路径需要根据实际情况进行修改。
  • 脚本需要在包含 mp4 文件的目录下运行。

该代码能够帮助你快速、便捷地修改文件名规则,并处理 'h_' 前缀的文件。如有任何问题,请随时提出。


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

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