Search code examples
pythonvideo-processingopencvbatch-rename

How to batch rename video files with quality information using python?


I was trying to write a program to rename all the video files of a folder. I just wanted to add video quality or dimension like (720p) or (1080p) or something like that to the end of the current file name. But I'm getting the following error:

Traceback (most recent call last):
  File "f:\Python Projects\Practice\mm.py", line 17, in <module>
    os.rename(file_name, f'{file_title} ({height}p){file_extension}')
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Video 1.mp4' -> 'Video 1 (1080p).mp4'

Here is my code:

import os
from cv2 import cv2

os.chdir(r'F:\Python Projects\Practice\Temp Files')

for file_name in os.listdir():
    # Getting Video Resolution
    with open(file_name, 'r') as f:
        f_string = str(f).split('\'')[1]
        video_path = f'F:\\Python Projects\\Practice\\Temp Files\\{f_string}'
        video = cv2.VideoCapture(video_path)
        height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # Getting the title
    file_title, file_extension = os.path.splitext(file_name)
    os.rename(file_name, f'{file_title} ({height}p){file_extension}')

Can anyone tell me how I can fix this problem? Thanks in advance... :)


Solution

  • The problem is that cv2.VideoCapture(video_path) opens your file as well. As this object continues to exist, the file is still open (even if it no longer is by your open(...) as f: once you exit the with block.)

    So, you have to do it explicitely with:

    video.release()