Home  >  Article  >  Backend Development  >  How to get the size and duration of a video file in Python?

How to get the size and duration of a video file in Python?

WBOY
WBOYforward
2023-04-22 22:25:152635browse

1. Prerequisite knowledge

A total of 3 Python libraries are needed here, namely os, pandas, and moviepy.

  • ① os: used to obtain files and file sizes in a certain directory;

  • ② pandas: used to extract the information , save to Excel;

  • ③ moviepy: used to get the duration in the video file;

Note: pandas and moviepy are third-party libraries, so we need to install them in advance using the following command.

pip install pandas
pip install moviepy

2. Complete code

① Import all libraries

import os
import pandas as pd
from moviepy.editor import VideoFileClip

② Obtain qualified files in the specified directory

useful_dir = []
for i in os.listdir():
    if i.endswith("wmv"):
        useful_dir.append(i)
useful_dir

The results are as follows:

How to get the size and duration of a video file in Python?

③ Custom time conversion function

def time_convert(seconds):
    M,H = 60,3600
    if seconds < M:
        return f&#39;00:00:0{seconds}&#39; if seconds < 10 else f&#39;00:00:{str(seconds)}&#39;
    elif seconds < H:
        _M = int(seconds//M)
        _S = int(seconds%M)
        return f&#39;00:{f"0{_M}" if _M < 10 else str(_M)}:{f"0{_S}" if _S < 10 else str(_S)}&#39;
    else:
        _H = int(seconds//H)
        _M = int(seconds%H//M)
        _S = int(seconds%H%M)
        return f&#39;{f"0{_H}" if _H < 10 else str(_H)}:{f"0{_M}" if _M < 10 else str(_M)}:{f"0{_S}" if _S < 10 else str(_S)}&#39;

Due to the VideoFileClip() method introduced below, the unit for obtaining the duration is seconds. Therefore, the seconds need to be converted into the appropriate "hours, minutes and seconds" format. If the time exceeds one minute, it is converted into "minutes: seconds"; if it exceeds one hour, it is converted into "hours: minutes: seconds" format.

④ Get the file size and duration

x = []
y = []
for i in useful_dir:
    dir_size = str(round(os.path.getsize(i)/1024/1024,1)) + "M"
    clip = VideoFileClip(i)
    dir_time = time_convert(clip.duration)
    x.append(dir_size)
    y.append(dir_time)
df = pd.DataFrame({"文件大小":x,"文件时长":y})
df

The results are as follows:

How to get the size and duration of a video file in Python?

⑤ Store the obtained data in Excel

df.to_excel("info.xlsx",index=False)

The final effect is as shown in the picture:

How to get the size and duration of a video file in Python?

The above is the detailed content of How to get the size and duration of a video file in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete