[Python] 纯文本查看 复制代码
import os
from moviepy.editor import VideoFileClip
def delete_short_videos(folder_path, min_duration=30):
"""
删除文件夹中时长小于min_duration秒的MP4视频
参数:
folder_path (str): 要处理的文件夹路径
min_duration (int): 最小保留时长(秒),默认为30秒
"""
deleted_count = 0
kept_count = 0
for filename in os.listdir(folder_path):
if filename.lower().endswith('.mp4'):
filepath = os.path.join(folder_path, filename)
try:
# 获取视频时长
with VideoFileClip(filepath) as video:
duration = video.duration
# 判断并删除
if duration < min_duration:
os.remove(filepath)
print(f"已删除: {filename} (时长: {duration:.2f}秒)")
deleted_count += 1
else:
print(f"保留: {filename} (时长: {duration:.2f}秒)")
kept_count += 1
except Exception as e:
print(f"处理文件 {filename} 时出错: {str(e)}")
print(f"\n处理完成: 删除了 {deleted_count} 个文件, 保留了 {kept_count} 个文件")
# 使用示例
folder_path = input("请输入要处理的文件夹路径: ")
delete_short_videos(folder_path) [Python] 纯文本查看 复制代码
import os
import subprocess
def get_video_duration_ffprobe(filepath):
"""使用ffprobe获取视频时长(秒)"""
cmd = [
'ffprobe', '-v', 'error', '-show_entries',
'format=duration', '-of',
'default=noprint_wrappers=1:nokey=1', filepath
]
try:
output = subprocess.check_output(cmd).decode('utf-8').strip()
return float(output)
except:
return None
def delete_short_videos_ffprobe(folder_path, min_duration=30):
"""
使用ffprobe删除短视频
参数:
folder_path (str): 要处理的文件夹路径
min_duration (int): 最小保留时长(秒),默认为30秒
"""
deleted_count = 0
kept_count = 0
for filename in os.listdir(folder_path):
if filename.lower().endswith('.mp4'):
filepath = os.path.join(folder_path, filename)
duration = get_video_duration_ffprobe(filepath)
if duration is None:
print(f"无法获取 {filename} 的时长,跳过")
continue
if duration < min_duration:
os.remove(filepath)
print(f"已删除: {filename} (时长: {duration:.2f}秒)")
deleted_count += 1
else:
print(f"保留: {filename} (时长: {duration:.2f}秒)")
kept_count += 1
print(f"\n处理完成: 删除了 {deleted_count} 个文件, 保留了 {kept_count} 个文件")
# 使用示例
folder_path = input("请输入要处理的文件夹路径: ")
delete_short_videos_ffprobe(folder_path)
变量名 类 型 静态 数组 备 注 all_mp4 文本型 0 i cmd 文本型 time_ 整数型
文件_枚举 ( “d:\mp4目录” ,
“*.mp4” , all_mp4, 真, ,
) 变量循环首 ( 取数组成员数 ( all_mp4
) , 1, -1, i
) cmd =
“d:\mp4目录\ffprobe.exe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 ” + all_mp4
[ i
] time_ =
到整数 ( 系统_取DOS执行结果 ( cmd,
) )
如果真 ( time_ < 30
) 调试输出 ( time_,
“删除” ) 变量循环尾 ( )