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
import os import pandas as pd from moviepy.editor import VideoFileClip
useful_dir = [] for i in os.listdir(): if i.endswith("wmv"): useful_dir.append(i) useful_dir
The results are as follows:
def time_convert(seconds): M,H = 60,3600 if seconds < M: return f'00:00:0{seconds}' if seconds < 10 else f'00:00:{str(seconds)}' elif seconds < H: _M = int(seconds//M) _S = int(seconds%M) return f'00:{f"0{_M}" if _M < 10 else str(_M)}:{f"0{_S}" if _S < 10 else str(_S)}' else: _H = int(seconds//H) _M = int(seconds%H//M) _S = int(seconds%H%M) return f'{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)}'
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.
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:
df.to_excel("info.xlsx",index=False)
The final effect is as shown in the picture:
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!