如何使用 python 批量重命名带有质量信息的视频文件?

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

我正在尝试编写一个程序来重命名文件夹中的所有视频文件。我只是想在当前文件名的末尾添加视频质量或尺寸,如 (720p) 或 (1080p) 或类似的东西。但我收到以下错误:

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'

这是我的代码:

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}')

谁能告诉我如何解决这个问题?提前致谢...:)

像这样。经过测试。使用

video.release() 

关闭用 cv2 打开的文件。

import os
from cv2 import cv2

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

for file_name in os.listdir():
    # Getting Video Resolution

    f = open(file_name, 'r')
    f_string = str(f).split('\'')[1]
    f.close()

    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))
    video.release()

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

问题是 cv2.VideoCapture(video_path) 也会打开您的文件。由于此对象继续存在,文件仍处于打开状态(即使退出 with 块后它不再由 open(...) as f: 打开。)

因此,您必须明确地使用:

video.release()

我已经简化了代码并且它工作得很好。我在这里分享我的代码。如果有人从我的代码中受益,那将是我的骄傲......:)

import os
from cv2 import cv2

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

for file_name in os.listdir():
    # Getting video quality
    video_path = f'{video_folder}\{file_name}'
    video = cv2.VideoCapture(video_path)
    width = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    video.release()

    # Getting title
    file_title, file_extension = os.path.splitext(file_name)
    new_file_name = f'{file_title} ({width}p){file_extension}'

    # Renaming the file
    os.rename(file_name, new_file_name)

print('Rename Successful!')