视频时长统计

视频时长统计

import os
import datetime
from moviepy.editor import VideoFileClip
import time

"""
  获取一个文件夹内视频长度的和
"""

def compute_video_time(path):
    type = ('.mp4')
    filelist = []

    for a, b, c in os.walk(path):
        for name in c:
            fname = os.path.join(a, name)
            if fname.endswith(type):
                filelist.append(fname)
    print("------开始计算时间------")
    ftime = 0.0
    count = 0
    for item in filelist:
        try:
            clip = VideoFileClip(item)
            ftime += clip.duration
            count = count + 1
            print("已完成%.2f" % ((count / filelist.__len__()) * 100) + "%")
            clip.reader.close()  # 防止出现错误:句柄无效
            clip.audio.reader.close_proc()
        except:
            print(item)
    print("总共%d个文件" % count)
    print(f'路径为: {path}')
    print("%d seconds: " % ftime, str(datetime.timedelta(seconds=ftime)))
    f = open('视频时长统计.txt', 'a')
    f.write(f'路径为:{path} \t 时间:{ftime/60} min \n')


if __name__ == "__main__":
    time1 = time.time()
    file_path = r'F:\20210501# 知识分类\20210501# 计算机\20210501# 培训视频_2021\20210501# Python教程\黑马5.0-python全套'
    sub_file_list = os.listdir(file_path)
    for i in sub_file_list:
        path = rf"{file_path}\{i}"
        compute_video_time(path)

        time2 = time.time()
        print(time2 - time1)


posted @ 2021-05-04 23:13  傀儡岁月  阅读(370)  评论(0编辑  收藏  举报