import os import subprocess import openpyxl import math

安装 openpyxl 模块

pip install openpyxl

安装 mediainfo 命令行工具

sudo apt-get install mediainfo

需要处理的视频文件夹

video_folder = '/home/115/up'

输出 Excel 文件名

excel_file = '/home/115/up/video_info.xlsx'

创建 Excel 文件

wb = openpyxl.Workbook() ws = wb.active ws.title = 'Video Info'

设置表头

headers = ['文件名', '大小', '时长', '分辨率', '码率', '帧率', '音频码率', '音频采样率', '格式'] for col, header in enumerate(headers, start=1): ws.cell(row=1, column=col, value=header)

获取视频文件列表

video_files = [os.path.join(video_folder, f) for f in os.listdir(video_folder) if f.endswith('.mp4')]

遍历所有视频文件,获取视频信息并写入 Excel 文件

for row, video_file in enumerate(video_files, start=2): # 获取文件名 file_name = os.path.basename(video_file)

# 获取文件大小并进行单位换算
size = os.path.getsize(video_file)
if size < 1024:
    size_str = f'{size} B'
elif size < 1024*1024:
    size_str = f'{size/1024:.2f} KiB'
elif size < 1024*1024*1024:
    size_str = f'{size/1024/1024:.2f} MiB'
else:
    size_str = f'{size/1024/1024/1024:.2f} GiB'

# 使用 mediainfo 获取视频信息和音频信息
video_result = subprocess.run(['mediainfo', '--Inform=Video;%Format%|%Width%x%Height%|%BitRate/String%|%FrameRate%|%Duration/String3%', video_file], stdout=subprocess.PIPE)
video_output = video_result.stdout.decode().strip()
audio_result = subprocess.run(['mediainfo', '--Inform=Audio;%BitRate/String%|%SamplingRate/String%', video_file], stdout=subprocess.PIPE)
audio_output = audio_result.stdout.decode().strip()

# 解析输出结果
format, resolution, bitrate, framerate, duration = video_output.split('|')
audiobitrate, audiosamplingrate = audio_output.split('|')

# 将时长取整
duration = duration.split('.')[0]
h, m, s = duration.split(':')
duration = f'{h}:{m}:{math.ceil(float(s))}'

# 写入 Excel 文件
ws.cell(row=row, column=1, value=file_name)
ws.cell(row=row, column=2, value=size_str) # 写入文件大小
ws.cell(row=row, column=3, value=duration)
ws.cell(row=row, column=4, value=resolution)
ws.cell(row=row, column=5, value=bitrate)
ws.cell(row=row, column=6, value=framerate)
ws.cell(row=row, column=7, value=audiobitrate) # 写入音频码率
ws.cell(row=row, column=8, value=audiosamplingrate) # 写入音频采样率
ws.cell(row=row, column=9, value=format)

保存 Excel 文件

wb.save(excel_file) print(f'视频信息已保存到 {excel_file}')

Python 代码优化:按指定顺序写入视频信息到 Excel 文件

原文地址: https://www.cveoy.top/t/topic/mz2p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录