Python3 代码:批量合并 MP4 文件并删除数字前缀
import os
import glob
from natsort import natsorted
# 当前文件夹下的所有 mp4 路径
L = []
dir_path = '/home/downloads'
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:
new_name = ''.join([i for i in os.path.splitext(os.path.basename(l))[0] if not i.isdigit()])
ts_file = os.path.join(os.path.dirname(l), new_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), ''.join([i for i in os.path.splitext(os.path.basename(l))[0] if not i.isdigit()]) + '.ts') for l in L])}}' '
'-acodec copy -vcodec copy -bsf:a aac_adtstoasc '
f"'{os.path.join(dir_path, ''.join([i for i in os.path.splitext(os.path.basename(L[0]))[0] if not i.isdigit()])[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)
代码功能:
- 读取目录下的所有 MP4 文件: 使用
os.walk遍历目录,并使用natsorted对文件进行自然排序。 - 删除文件名中的数字前缀: 使用列表推导,将文件名中非数字的字符提取出来作为新的文件名。
- 生成 ffmpeg 命令: 使用
f-string格式化字符串,生成将每个 MP4 文件转换为 TS 文件的 ffmpeg 命令。 - 生成合并命令: 使用
f-string格式化字符串,生成将所有 TS 文件合并为一个 MP4 文件的 ffmpeg 命令。 - 执行 ffmpeg 命令: 使用
os.system执行 ffmpeg 命令。 - 删除临时 TS 文件: 使用
glob模块查找所有 TS 文件并使用os.remove删除。
使用说明:
- 将代码中的
dir_path修改为实际 MP4 文件所在的目录路径。 - 运行代码,代码将自动完成所有操作,并输出一个合并后的 MP4 文件。
注意:
- 代码需要安装
natsort模块,可以使用pip install natsort命令进行安装。 - 确保系统已经安装了
ffmpeg工具。 - 代码会删除原始的 MP4 文件,请提前备份重要文件。
原文地址: https://www.cveoy.top/t/topic/nCdz 著作权归作者所有。请勿转载和采集!