Python3 代码优化:提高视频文件分析效率
以下是对 Python3 代码的优化建议,旨在提高视频文件分析的效率和可读性。
- 使用列表推导式替代 for 循环
在获取视频文件列表的循环中,可以使用列表推导式来替代 for 循环,可以提高代码的可读性和性能。
示例代码:
video_files = [os.path.join(root, file) for root, dirs, files in os.walk(video_folder) for file in files if any(file.endswith(format) for format in supported_formats)]
- 使用 f-strings 替代字符串拼接
在打印文件信息时,使用 f-strings 来替代字符串拼接,可以提高代码的可读性和性能。
示例代码:
print(f'{file_name}, {size_str}, {duration}, {video_info[1]}, {bitrate}, {framerate}, {' / '.join(audio_lang)}, {ratio}')
- 使用 os.path.splitext 替代字符串切片
在获取文件名和判断视频格式时,可以使用 os.path.splitext 来替代字符串切片,可以提高代码的可读性和健壮性。
示例代码:
# 获取文件名
file_name = os.path.splitext(os.path.basename(video_file))[0]
# 判断视频格式
if os.path.splitext(video_file)[1] not in supported_formats:
continue
- 使用 with 语句管理资源
在使用 subprocess 运行外部命令时,建议使用 with 语句来管理资源,可以自动关闭文件句柄和清理资源,避免资源泄露和错误。
示例代码:
with subprocess.Popen(['mediainfo', '--Inform=Video;%Format%|%Width%x%Height%|%BitRate/String%|%FrameRate%|%Duration/String3%', video_file], stdout=subprocess.PIPE) as video_process:
video_output = video_process.stdout.decode().strip()
with subprocess.Popen(['mediainfo', '--Inform=Audio;%BitRate/String%|%SamplingRate/String%|%Language/String%', video_file], stdout=subprocess.PIPE) as audio_process:
audio_output = audio_process.stdout.decode().strip()
- 使用 format_duration 函数格式化时间
在格式化视频时长时,建议使用 format_duration 函数来格式化时间,可以提高代码的可读性和健壮性。
示例代码:
def format_duration(duration_str):
h, m, s = map(int, duration_str.split(':'))
return f'{h:02d}:{m:02d}:{s:02d}'
# 格式化视频时长
duration = format_duration(video_info[4].split('.')[0])
通过应用这些优化建议,可以使代码更加简洁、高效,并提升代码的可维护性。
原文地址: https://www.cveoy.top/t/topic/mHj2 著作权归作者所有。请勿转载和采集!