Python 3 Excel 处理: M 列左对齐和 total_count 项加粗
import os
import re
import subprocess
import openpyxl
import math
from openpyxl.styles import Font, PatternFill, Alignment
# 视频格式
supported_formats = [
'.mp4',
'.avi',
'.mkv',
'.wmv',
'.mov',
'.flv',
'.m2ts',
'.ts',
'.rm',
'.rmvb',
'.vob',
'.3gp',
'.webm',
'.hdmov',
'.mp4v',
'.mpv4',
'.divx',
'.xvid',
'.f4v',
'.mpeg',
'.asf',
'.asx',
'.m2t',
]
# 输出 Excel 路径
excel_folder = '.'
# 输出 Excel 文件名
excel_file = 'video_info.xlsx'
# 正则表达式匹配码率数据中的空格
pattern = re.compile(r'(\d+)\s+(\d+)')
# 创建 Excel 文件
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Video Info'
# 锁定表头
ws.freeze_panes = 'A2'
# 设置表头样式
header_font = Font(bold=True, color='800080') # 紫色
header_fill = PatternFill('solid', fgColor='C5E0B4')
header_alignment = Alignment(horizontal='center', vertical='center')
headers = [
'文件名',
'文件路径',
'格式',
'大小',
'时长',
'分辨率',
'码率',
'帧率',
'音频码率',
'音频采样率',
'音频语言',
'压缩比率',
'文件总数',
]
for col, header in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = header_alignment
# 处理失败文件个数
failed_count = 0
# 总计处理文件数
total_count = 0
# 遍历所有视频文件
success_count = 0
row = 2 # 从第二行开始写入数据
def process_video(video_file):
global success_count, row, failed_count
try:
# 获取文件名
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%|%Language/String%',
video_file,
],
stdout=subprocess.PIPE,
)
audio_output = audio_result.stdout.decode().strip()
# 解析输出结果
video_info = video_output.split('|')
audio_info = audio_output.split('|')
# 处理多音轨情况
audio_bitrate = []
audio_sampling_rate = []
audio_lang = []
for i in range(len(audio_info) // 3):
audio_bitrate.append(audio_info[i * 3])
audio_sampling_rate.append(audio_info[i * 3 + 1])
audio_lang.append(audio_info[i * 3 + 2])
# 时长取整
duration = video_info[4].split('.')[0]
h, m, s = duration.split(':')
duration = f'{h}:{m}:{str(s).zfill(2)}'
# 以分钟计算的时长 2
duration_minutes = int(h) * 60 + int(m) + math.ceil(float(s)) / 60
# 计算压缩比率
ratio = round(duration_minutes / size * 1000000000, 2)
# 使用正则表达式替换码率数据中第一个数字和第二个数字之间的空格
bitrate = re.sub(pattern, r'\1\2', video_info[2])
# 写入 Excel 文件
ws.cell(row=row, column=1, value=file_name)
ws.cell(row=row, column=2, value=os.path.dirname(video_file)) # 写入文件路径
ws.cell(row=row, column=3, value=video_info[0])
ws.cell(row=row, column=4, value=size_str)
ws.cell(row=row, column=5, value=duration)
ws.cell(row=row, column=6, value=video_info[1])
ws.cell(row=row, column=7, value=bitrate)
ws.cell(row=row, column=8, value=video_info[3])
ws.cell(row=row, column=9, value=' / '.join(audio_bitrate))
ws.cell(row=row, column=10, value=' / '.join(audio_sampling_rate))
ws.cell(row=row, column=11, value=' / '.join(audio_lang))
ws.cell(row=row, column=12, value=ratio)
ws.cell(row=2, column=13, value=total_count) # 写入文件总数
# 打印进度
success_count += 1
row += 1
except Exception as e:
# 处理失败,跳过并打印文件名和具体错误信息
failed_count += 1
print(f'处理文件 {video_file} 时失败:{e}')
# 将失败的文件写入到err.txt
with open('err.txt', 'a') as f:
f.write(f'{video_file}\n')
return False
return True
def process_folder(video_folder):
global total_count
# 获取视频文件列表(包括子目录)
video_files = []
for root, dirs, files in os.walk(video_folder):
for file in files:
for format in supported_formats:
if file.endswith(format):
video_files.append(os.path.join(root, file))
break
total_count = len(video_files)
for i, video_file in enumerate(video_files, start=1):
if process_video(video_file):
print(f'已处理 {success_count}/{total_count} 共计', end='\r')
else:
print(f'处理文件 {i}/{total_count} 时失败', end='\r')
print(f'已处理 {success_count}/{total_count} 共计')
# 文件路径
path = input('请输入文件路径:')
if os.path.isfile(path):
process_video(path)
total_count += 1
elif os.path.isdir(path):
process_folder(path)
# 调整L列左对齐
l_col = ws['L']
for cell in l_col:
cell.alignment = Alignment(horizontal='left') # 左对齐
# 固定列宽
for col in ws.columns:
col_letter = col[0].column_letter
if col_letter not in ['C', 'H']: # 不固定格式、帧率列的宽度
ws.column_dimensions[col_letter].width = 11
# 保存 Excel 文件
if not os.path.exists(excel_folder):
os.makedirs(excel_folder)
excel_file_path = os.path.join(excel_folder, excel_file)
wb.save(excel_file_path)
# 设置 M 列左对齐
m_col = ws['M']
for cell in m_col:
cell.alignment = Alignment(horizontal='left')
# 设置 total_count 项字体加粗
total_count_cell = ws.cell(row=2, column=13)
total_count_cell.font = Font(bold=True)
# 打印处理失败文件个数和总计处理文件数
print(
f'已完成,处理成功 {success_count} 个文件,处理失败 {failed_count} 个文件,视频信息已保存到 {excel_file_path}'
)
该脚本执行以下操作:
- 导入必要的库:
os,re,subprocess,openpyxl,math,openpyxl.styles - 定义视频格式列表:
supported_formats - 设置输出 Excel 文件的路径和文件名:
excel_folder和excel_file - 创建 Excel 工作簿和工作表:
wb和ws - 锁定表头:
ws.freeze_panes = 'A2' - 设置表头样式: 字体加粗、颜色为紫色、填充颜色为浅绿色,水平和垂直居中
- 定义表头:
headers - 遍历表头并设置样式: 将表头写入第一行,并设置字体、填充颜色和对齐方式
- 定义处理视频文件的函数:
process_video - 定义处理文件夹的函数:
process_folder - 输入文件路径: 从用户获取文件路径
- 处理视频文件或文件夹: 根据输入路径,调用
process_video或process_folder函数 - 将
total_count写入 Excel 文件: 在第二行第 13 列写入total_count - 设置 M 列左对齐: 遍历 M 列所有单元格,并设置其对齐方式为左对齐
- 设置
total_count项字体加粗: 设置第二行第 13 列单元格的字体为加粗 - 保存 Excel 文件: 将 Excel 文件保存到指定的路径
- 打印处理结果: 打印处理成功和失败的文件数量,以及保存到的 Excel 文件路径。
该脚本还使用 mediainfo 命令来获取视频信息,并使用正则表达式来匹配和处理码率数据中的空格。它还实现了进度条功能,以便用户能够跟踪处理进度。
您可以在脚本中修改相关参数,例如 excel_folder、excel_file 和 supported_formats,以满足您的需求。
使用说明:
- 将脚本保存为
.py文件,例如excel_processing.py - 运行脚本,例如
python excel_processing.py - 输入文件路径
- 等待脚本处理完文件,Excel 文件将保存到指定的路径。
注意:
- 需要安装
openpyxl库,可以使用pip install openpyxl命令进行安装 - 需要安装
mediainfo命令,可以从 https://mediaarea.net/en/MediaInfo 网站下载并安装 - 脚本默认将失败的文件写入到
err.txt文件中。 - 脚本使用
subprocess.run函数来执行mediainfo命令,需要确保mediainfo命令已添加到系统环境变量中。
希望这能够帮助您更好地理解该脚本的代码和功能。
原文地址: https://www.cveoy.top/t/topic/mFSy 著作权归作者所有。请勿转载和采集!