Python代码在Windows上运行报错IndexError: list index out of range的解决方法
该代码在Windows上运行出错的原因是在生成concat_command命令时,L为空,导致拼接命令出错。可以在生成concat_command之前添加判断L是否为空的语句,如果为空,则直接输出'No mp4 files found in the directory.',否则再生成拼接命令。修正后的代码如下:
import os
import glob
from natsort import natsorted
# 存储当前文件夹下的所有mp4文件路径
L = []
dir_path = 'E:/home/up'
for root, dirs, files in os.walk(dir_path):
files = natsorted(files)
for file in files:
# 只处理mp4文件
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.basename(l).replace('.mp4', '.ts'))
commands.append(f'ffmpeg -i '{l}' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb '{ts_file}'')
if len(L) > 0:
concat_files = [os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')) for l in L]
if len(concat_files) > 0:
concat_command = f'ffmpeg -i 'concat:{'|'.join(concat_files)}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc '{os.path.join(dir_path, 'output.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)
else:
print('No mp4 files found in the directory.')
else:
print('No mp4 files found in the directory.')
代码修正后,在生成concat_command命令之前判断了L是否为空,如果为空,则直接输出'No mp4 files found in the directory.',避免了拼接命令出错的情况。
原文地址: https://www.cveoy.top/t/topic/nzTJ 著作权归作者所有。请勿转载和采集!