Skip to content

Detecting 9:16 Aspect Ratio in MP4 Videos using Python – If a Video ready for TikTok or Youtube Short

When managing a library of videos, it’s often beneficial to organize them based on their aspect ratios. This can be particularly helpful when you’re dealing with content intended for specific screen resolutions or platforms. In this tutorial, we’ll explore how to determine if an MP4 video has a 9:16 aspect ratio using Python.


Before we delve into the code, let’s briefly discuss what an aspect ratio is. Aspect ratio is the proportional relationship between the width and height of an image or video. A 9:16 aspect ratio, for example, means that for every 9 units of width, there are 16 units of height.

Understanding the Code

Step 1: Importing Necessary Libraries

import os
import shutil
from moviepy.editor import VideoFileClip

Here, we import essential libraries:

  • os and shutil for handling file operations.
  • VideoFileClip from moviepy.editor to extract video metadata.

Step 2: Retrieving Video Dimensions

def get_video_dimensions(file_path):
clip = VideoFileClip(file_path)
dimensions = clip.size
return dimensions

This function takes a file path as input, opens the video clip, retrieves its dimensions, and returns them. Remember to close the clip after obtaining the dimensions to free up resources.

Step 3: Categorizing Videos based on Aspect Ratio

def move_to_916_folder(file_path):
destination_folder_916 = "916"
destination_folder_non916 = "non916"

dimensions = get_video_dimensions(file_path)

if dimensions[0] / dimensions[1] == 9 / 16:
destination_folder = destination_folder_916
destination_folder = destination_folder_non916
if not os.path.exists(destination_folder):
destination_path = os.path.join(destination_folder, os.path.basename(file_path))
shutil.move(file_path, destination_path)
print(f"Moved {file_path} to {destination_path}")
except PermissionError:
print(f"PermissionError: File {file_path} is in use. Skipping.")

In this function, we categorize videos based on their aspect ratios. If the ratio is 9:16, the video is moved to a folder named “916”; otherwise, it’s moved to a folder named “non916”.

Step 4: Main Function

def main():
current_directory = os.getcwd()
video_files = [f for f in os.listdir(current_directory) if f.endswith(".mp4")]
for video_file in video_files:
file_path = os.path.join(current_directory, video_file)

if __name__ == "__main__":

The main function retrieves all MP4 files in the current directory and iterates over them, calling the move_to_916_folder function for each file.


In this tutorial, we’ve learned how to use Python to verify if an MP4 video has a 9:16 aspect ratio. By organizing videos based on their aspect ratios, you can streamline your workflow and ensure that your content is optimized for the intended display.

Happy coding!