Example code for grouping video file resolution using python

  • 2021-12-09 09:15:36
  • OfStack

In normal work, our directory has a lot of video files. If you don't have a good video classification habit, it will take time to find video materials. By classifying the video resolution path, you can quickly find the video resolution you want when you need it. Of course, manual classification is a kind of time-consuming and laborious work, which is to improve our work efficiency through software or program.

Code sharing


import os
import subprocess
import json
import shutil
import datetime

def get_files(file_dir):
    for root, dirs, files in os.walk(file_dir):
        if len(files) > 0:
            #  Get the picture path 
            for f in files:
                if f.endswith(".mp4"):
                    p = os.path.join(root, f)
                    h, w, t = get_video_info(p)

                    new_dir = os.path.realpath(
                        "{}\{}x{}".format(file_dir, h, w))
                    if not os.path.exists(new_dir):
                        os.makedirs(new_dir)
                    shutil.move(p, os.path.join(new_dir, "{}.mp4".format(t)))

def get_video_info(file_path):

    cmd = "ffprobe -v quiet -print_format json -show_streams -i {}".format(
        file_path)

    with open('output.json', 'w') as f:
        subprocess.call(cmd, stdout=f)

    with open('output.json', 'r') as f:
        streams = json.load(f)
        for i in streams["streams"]:
            if i['codec_type'] == "video":
                print(file_path)
                t2 = ""
                try:
                    t1 = datetime.datetime.strptime(
                        i['tags']['creation_time'], "%Y-%m-%dT%H:%M:%S.%f%z")
                    t2 = datetime.datetime.strftime(t1, '%Y%m%d%H%M%S')
                except KeyError:
                    t2 = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                return i['height'], i['width'], t2
            else:
                continue

if __name__ == "__main__":
    file_dir = input("dir:")
    get_files(file_dir)

The code uses the ffprobe Get video information

Original: http://www.rencaixiu.cn/archives/811/


Related articles: