111111

python 获取目录视频时长,大小

#!/usr/bin/python
# -*- coding:utf-8 -*-


import os
import sys
import re
import xlwt
import csv
from moviepy.editor import *
#from moviepy.editor import VideoFileClip

file_dir = "/ftpdir/data1/" #定义文件目录
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Worksheet')


class FileCheck():

    def __init__(self):
        self.file_dir = file_dir

    def get_filesize(self,filename):
        u"""
        获取文件大小(M: 兆)
        """
        file_byte = os.path.getsize(filename)
        return self.sizeConvert(file_byte)

    def get_file_times(self,filename):
        u"""
        获取视频时长(s:秒)
        """
        clip = VideoFileClip(filename)
        file_time = self.timeConvert(clip.duration)
        return file_time

    def sizeConvert(self,size):# 单位换算
        K, M, G = 1024, 1024**2, 1024**3
        if size >= G:
            a = str(size/G)
            a = str(int(a.split('.')[0]))

            return a +'G Bytes'
            #return str(size/G)+'G Bytes'
        elif size >= M:
            a = str(size/M)
            a = str((int(a.split('.')[0])+1))

            return a +'M Bytes'
        elif size >= K:
            return str(size/K)+'K Bytes'
        else:
            return str(size)+'Bytes'

    def timeConvert(self,size):# 单位换算
        M, H = 60, 60**2
        if size < M:
            return str(size)+u'秒'
        if size < H:
            return u'%s分钟%s秒'%(int(size/M),int(size%M))
        else:
            hour = int(size/H)
            mine = int(size%H/M)
            second = int(size%H%M)
            tim_srt = u'%s小时%s分钟%s秒'%(hour,mine,second)
            return tim_srt

    def get_all_file(self):
        u"""
        获取视频下所有的文件
        """
        #for root, dirs, files in os.walk(file_dir):  
            #return files #当前路径下所有非目录子文件
        ds = list(os.walk(file_dir))
        list_a = []
        with open('./data_duration.csv','a',encoding='utf-8') as f:
            for root,dirs,files in ds:
                for file in files:
                    file_path = '{}/{}'.format(root,file)
                    if re.match('/ftpdir/data1/.*/(\d+)(.ts|.mp4)',file_path):
                        a = self.get_file_times(file_path)
                        b = self.get_filesize(file_path)
                        f.write('{}-----{}-----{}\n'.format(file_path,a,b))


obj = FileCheck()
obj_a = obj.get_all_file()
print(obj_a)

  

posted @ 2019-03-14 13:59  赵SIR  阅读(3651)  评论(1编辑  收藏  举报