Python代码在Windows上运行报错IndexError: list index out of range,修正及完整代码
以下是修正后的完整代码:
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_command = f'ffmpeg -i \"concat:{'|' .join([os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')) for l in L])}\" -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.')
代码修正说明:
在原代码中,当目录下没有MP4文件时,L为空列表,导致后续使用L索引时出现IndexError: list index out of range错误。
修正代码添加了对L长度的判断,只有当L非空时才会执行合并操作。
代码功能:
- 遍历指定目录,获取所有MP4文件路径并存储到L列表中。
- 遍历L列表,生成FFmpeg命令,将每个MP4文件转换为TS文件。
- 生成FFmpeg命令,将所有TS文件合并成一个MP4文件。
- 执行所有FFmpeg命令。
- 删除所有生成的TS文件。
运行环境:
- Python 3.x
- FFmpeg
- natsort库 (pip install natsort)
使用说明:
- 修改代码中的
dir_path为需要处理的目录路径。 - 确保FFmpeg已安装并配置好环境变量。
- 运行代码,即可将目录下的所有MP4文件合并成一个名为
output.mp4的文件。
注意事项:
- 代码中使用了FFmpeg命令,需要确保FFmpeg已安装并配置好环境变量。
- 代码中的
output.mp4文件名可根据需要修改。 - 该代码仅适用于合并同类型(MP4)视频文件,如果需要合并其他类型的文件,需要修改FFmpeg命令。
原文地址: https://www.cveoy.top/t/topic/nzTz 著作权归作者所有。请勿转载和采集!