为 Python3 代码增加跳过处理失败并文件继续执行,并打印处理失败的文件功能/n/npython/nimport os/nimport re/nimport subprocess/nimport openpyxl/nimport math/nfrom openpyxl.styles import Font, PatternFill, Alignment/n/n/n# 视频格式/nsupported_formats = ['.mp4', '.avi', '.mkv', '.wmv', '.mov', '.flv', '.m2ts', '.ts', '.rm', '.rmvb',/n '.vob', '.3gp', '.webm', '.hdmov', '.mp4v', '.mpv4', '.divx', '.xvid', '.f4v',/n '.mpeg', '.asf', '.asx', '.m2t']/n# 视频文件夹/nvideo_folder = input('请输入文件夹路径:')/n# 输出Excel路径/nexcel_folder = '.'/n# 输出Excel文件名/nexcel_file = 'video_info.xlsx'/n# 正则表达式匹配码率数据中的空格/npattern = re.compile(r'(/d+)/s+(/d+)')/n# 创建Excel文件/nwb = openpyxl.Workbook()/nws = wb.active/nws.title = 'Video Info'/n/n/n# 设置表头样式/nheader_font = Font(bold=True, color='800080') # 紫色/nheader_fill = PatternFill('solid', fgColor='C5E0B4')/nheader_alignment = Alignment(horizontal='center', vertical='center')/nheaders = ['文件名', '文件路径', '格式', '大小', '时长', '分辨率', '码率', '帧率', '音频码率', '音频采样率', '音频语言', '压缩比率']/nfor col, header in enumerate(headers, start=1):/n cell = ws.cell(row=1, column=col, value=header)/n cell.font = header_font/n cell.fill = header_fill/n cell.alignment = header_alignment/n/n# 锁定表头/nws.freeze_panes = 'A2'/n/n# 获取视频文件列表(包括子目录)/nvideo_files = []/nfor root, dirs, files in os.walk(video_folder):/n for file in files:/n for format in supported_formats:/n if file.endswith(format):/n video_files.append(os.path.join(root, file))/n break/n/n# 遍历所有视频文件/nfor row, video_file in enumerate(video_files, start=2):/n try:/n # 获取文件名/n file_name = os.path.basename(video_file)/n/n # 获取文件大小并进行单位换算/n size = os.path.getsize(video_file)/n if size < 1024:/n size_str = f'{size} B'/n elif size < 1024 * 1024:/n size_str = f'{size / 1024:.2f} KiB'/n elif size < 1024 * 1024 * 1024:/n size_str = f'{size / 1024 / 1024:.2f} MiB'/n else:/n size_str = f'{size / 1024 / 1024 / 1024:.2f} GiB'/n/n # 使用mediainfo获取视频信息 / 音频信息/n video_result = subprocess.run(['mediainfo', '--Inform=Video;%Format%|%Width%x%Height%|%BitRate/String%|%FrameRate%|%Duration/String3%', video_file], stdout=subprocess.PIPE)/n video_output = video_result.stdout.decode().strip()/n audio_result = subprocess.run(['mediainfo', '--Inform=Audio;%BitRate/String%|%SamplingRate/String%|%Language/String%', video_file], stdout=subprocess.PIPE)/n audio_output = audio_result.stdout.decode().strip()/n/n # 解析输出结果/n format, resolution, bitrate, framerate, duration = video_output.split('|')/n audiobitrate, audiosamplingrate, audiolang = audio_output.split('|')/n/n # 时长取整/n duration = duration.split('.')[0]/n h, m, s = duration.split(':')/n duration = f'{h}:{m}:{math.ceil(float(s))}'/n/n # 以分钟计算的时长 2/n duration_minutes = int(h) * 60 + int(m) + math.ceil(float(s)) / 60/n/n # 计算压缩比率/n ratio = round(duration_minutes / size * 1000000000, 2)/n/n # 使用正则表达式替换码率数据中第一个数字和第二个数字之间的空格/n bitrate = re.sub(pattern, r'//1//2', bitrate)/n/n # 写入Excel文件/n ws.cell(row=row, column=1, value=file_name)/n ws.cell(row=row, column=2, value=os.path.dirname(video_file)) # 写入文件夹路径/n ws.cell(row=row, column=3, value=format)/n ws.cell(row=row, column=4, value=size_str) # 写入文件大小/n ws.cell(row=row, column=5, value=duration)/n ws.cell(row=row, column=6, value=resolution)/n ws.cell(row=row, column=7, value=bitrate)/n ws.cell(row=row, column=8, value=framerate)/n ws.cell(row=row, column=9, value=audiobitrate)/n ws.cell(row=row, column=10, value=audiosamplingrate)/n ws.cell(row=row, column=11, value=audiolang)/n ws.cell(row=row, column=12, value=ratio)/n/n # 打印进度/n print(f'已处理 {row-1}/{len(video_files)} 共计', end='//r')/n/n except Exception as e:/n # 处理失败,跳过并打印文件名/n print(f'处理文件 {video_file} 失败:{e}')/n/n# 调整L列左对齐/nl_col = ws['L']/nfor cell in l_col:/n cell.alignment = Alignment(horizontal='left') # 左对齐/n/n# 固定列宽/nfor col in ws.columns:/n col_letter = col[0].column_letter/n if col_letter not in ['']: # 不固定文件夹路径、格式、音频语言列的宽度/n ws.column_dimensions[col_letter].width = 11/n/n# 保存Excel文件/nif not os.path.exists(excel_folder):/n os.makedirs(excel_folder)/nexcel_file_path = os.path.join(excel_folder, excel_file)/nwb.save(excel_file_path)/nprint(f'已处理完所有视频文件,视频信息已保存到 {excel_file_path}')/n/n/n/n代码功能:/n/n1. 跳过处理失败文件: 使用 try...except 语句捕获异常,并在处理失败时打印错误信息,并跳过该文件的处理,继续处理下一个文件。/n2. 打印处理失败的文件名:except 块中,打印处理失败的文件名和异常信息,方便用户定位问题。/n/n代码优点:/n/n1. 提高程序稳定性: 错误处理机制可以确保程序在遇到错误时不会崩溃,并继续处理其他文件。/n2. 方便调试: 打印错误信息和文件名,可以帮助用户快速定位问题,进行调试。/n/n代码使用方式:/n/n1. 将代码保存为 .py 文件,例如 video_info.py/n2. 在命令行中运行代码,例如 python video_info.py/n3. 程序会提示用户输入视频文件夹路径,并自动处理文件夹中的所有视频文件,并将信息保存到 video_info.xlsx 文件中。/n/n代码没有语法错误。

Python3 代码优化:跳过处理失败文件并继续执行,打印失败文件名

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

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