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:
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(dir_path, ''.join([i for i in os.path.splitext(os.path.basename(L[0]))[0] if not i.isdigit()]).replace('00', '-', 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)
代码功能:
- 遍历目录: 遍历指定目录
/home/downloads下的所有 MP4 文件,并按照自然排序方式存储路径到列表L中。 - 生成 ffmpeg 命令: 使用
ffmpeg命令将每个 MP4 文件转换为 TS 格式,并生成相应的命令存储到列表commands中。 - 合并 TS 文件: 使用
ffmpeg命令将所有 TS 文件合并成一个新的 MP4 文件,并将文件名修改为去除了数字并大写首字母后的结果。 - 删除 TS 文件: 删除所有生成的 TS 文件。
代码优化:
- 使用
natsorted模块对文件名进行自然排序,确保文件按照正确的顺序合并。 - 使用
os.path.splitext函数获取文件名和扩展名,并使用os.path.basename函数获取文件名。 - 使用字符串方法
replace和upper对文件名进行修改。 - 使用
''.join([i for i in ... if not i.isdigit()])来去除文件名中的数字。 - 使用
f''字符串格式化语法来简化命令生成。 - 使用
os.system函数执行 ffmpeg 命令。
使用方法:
- 确保系统已安装
ffmpeg和natsort模块。 - 将代码保存为 Python 文件,例如
merge_mp4.py。 - 运行代码:
python merge_mp4.py。
注意:
- 请确保
dir_path指向正确的目录路径。 - 此代码仅适用于 MP4 文件合并,其他格式的文件可能需要调整命令。
- 代码中使用
os.system函数执行命令,可能存在安全风险,建议使用更安全的命令执行方式。
原文地址: https://www.cveoy.top/t/topic/nCcE 著作权归作者所有。请勿转载和采集!