统计指定目录下所有mp4文件的时长(包含子目录下的文件)

 1 # -*- coding:utf-8 -*-
 2 # Author :Zcb
 3 
 4 import os
 5 from moviepy.editor import VideoFileClip
 6 
 7 file_Dir = u"e:\\test" #加个u 是表示unicode 一般用在中文字符前
 8 sum_time =0
 9 
10 class FileCheck():
11     def __init__(self):
12         self.file_dir = file_Dir
13 
14     def get_fileSize(self,fileName):
15         """
16             获取文件大小
17         """
18         file_Byte = os.path.getsize(fileName)
19         return self.sizeConvert(file_Byte)
20 
21     def get_file_Times(self,filename):
22         """
23             获取视频时长
24         """
25         global sum_time
26         clip = VideoFileClip(filename)
27         sum_time +=clip.duration
28         file_Times = self.timeConvert(clip.duration)
29         clip.close()  #可以防止程序因为文件过多而报错
30         return file_Times
31     def sizeConvert(self,size): #单位换算
32         K,M,G = 1024,1024**2,1024**3
33         if size >=G:
34             return "{:.3f}G".format(size/G)
35         elif size >=M:
36             return "{:.3f}M".format(size/M)
37         elif size >=K:
38             return "{:.3f}K".format(size/K)
39         else:
40             return "{:.3f}Bytes".format(size)
41     def timeConvert(self,size): #单位换算
42         M ,H = 60,60**2
43         if size <M:
44             return "{:.3f}s".format(size)
45         if size <H:
46             return "{:}m{:.3f}s".format(int(size//M),size%M)
47         else:
48             hour = size//H
49             min = size%H//M
50             sec = size%H%M
51             return "{}h{}m{:.3f}s".format(int(hour),int(min),sec)
52     def get_all_file(self):
53         """
54             获取视频下的所有文件
55         """
56         ls_file =[]
57         for root,dirs,files in os.walk(file_Dir):
58             for file in files:
59                 if "mp4" in file: #只添加mp4文件
60                     ls_file.append(os.path.join(root,file))#当前路径下所有非目录子文件
61         return ls_file
62 print("============开始,文件较多,请耐心等待...")
63 fc = FileCheck()
64 
65 fc.get_all_file()
66 files = fc.get_all_file()
67 #print(files)  files 是放文件全名的列表
68 for file in files:
69     file_size = fc.get_fileSize(file)
70     file_times= fc.get_file_Times(file)
71     print("{} {} {}".format(file,file_size,file_times))
72 print("总时长:{}h{}m{:.3f}s".format(int(sum_time/3600),int(sum_time%3600//60),sum_time%3600%60))

主要是运用moviepy 库,也利用了os库获取指定目录下的所有mp4文件

注:参考文档:https://blog.csdn.net/xiaomahuan/article/details/78783174

猜你喜欢

转载自www.cnblogs.com/zach0812/p/11277987.html
今日推荐