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)

删除output_dir目录下以'h_'开头的文件名

for file in glob.glob(os.path.join(output_dir, 'h_*')): os.rename(file, os.path.join(output_dir, file.replace('h_', '')))

生成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 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('0123456789')[0]):] os.rename(mp4_file, os.path.join(output_dir, new_file_name))

Python3 代码优化:删除目录下以'h_'开头的文件名

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

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