使用Python自动统计视频文件时长、大小

 在工作中有时需要统计大量视频的时长,如果视频量少的话,我们可以手工进行统计;超过上百个视频的话,我们就得使用代码实现。

将要统计的视频放在一个文件夹内,同时设置输出文件位置和文件名。

注意事项:该代码需要安装ffmpeg文件,解压后将文件bin目录添加到系统环境变量。

import os
import subprocess
import pandas as pd
from datetime import timedelta

# 定义函数获取视频时长
def get_duration(video_path):
    cmd = f"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {video_path}"
    duration_str = subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
    duration = float(duration_str)
    hours, remainder = divmod(duration, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{int(hours)}小时{int(minutes)}分{int(seconds)}秒"

# 定义函数获取文件夹下所有视频文件路径
def get_all_video_paths(folder_path):
    video_paths = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".mp4") or file.endswith(".avi") or file.endswith(".mkv"):
                video_paths.append(os.path.join(root, file))
    return video_paths

# 定义函数获取视频大小
def get_video_size(video_path):
    size_str = subprocess.check_output(f"ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 {video_path}", shell=True).decode("utf-8").strip()
    size = int(size_str)
    if size < 1024 * 1024 * 1024:
        return "{:.2f}MB".format(size / (1024 * 1024))
    else:
        return "{:.2f}GB".format(size / (1024 * 1024 * 1024))

# 定义函数将结果输出到excel文件中
def output_to_excel(video_paths, output_file):
    data = []
    for path in video_paths:
        duration = get_duration(path)
        size = get_video_size(path)
        data.append({"视频名称": os.path.basename(path), "时长": duration, "大小": size})
    df = pd.DataFrame(data)
    df.to_excel(output_file, index=False)

if __name__ == '__main__':
    folder_path = r'C:\Users\Administrator\Desktop\视频文件' # 视频文件夹路径
    output_file = r'C:\Users\Administrator\Desktop\视频文件\视频统计002.xlsx' # 输出的excel文件路径
    video_paths = get_all_video_paths(folder_path)
    output_to_excel(video_paths, output_file)

以下为示例视频统计结果,供大家参考。

视频名称时长大小
001.mp40小时0分7秒2.35MB
002.mp40小时0分15秒3.84MB
003.mp40小时0分23秒5.73MB
006.mp40小时0分23秒5.82MB
007.mp40小时0分16秒4.00MB

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值