Python 批量将 AVI 文件转换为 MP4:带进度条和跳过已转换文件
使用 Python 编写程序,枚举目录下所有 AVI 文件并将其转换为同名 MP4 文件。该程序使用进度条显示转换进度,并且可以跳过已存在且大小不为 0 的 MP4 文件。\n\n代码示例:\n\npython\nimport os\nimport subprocess\nfrom tqdm import tqdm\n\ndef convert_avi_to_mp4(avi_file):\n mp4_file = avi_file[:-3] + 'mp4'\n if os.path.exists(mp4_file) and os.path.getsize(mp4_file) != 0:\n return\n subprocess.run(['ffmpeg', '-i', avi_file, mp4_file])\n os.remove(avi_file)\n\ndef main(directory):\n for root, dirs, files in os.walk(directory):\n for file in tqdm(files):\n if file.endswith('.avi'):\n avi_file = os.path.join(root, file)\n convert_avi_to_mp4(avi_file)\n\nif __name__ == '__main__':\n directory = '/path/to/directory' # 替换为你的目录路径\n main(directory)\n\n\n安装依赖项:\n\n\npip install ffmpeg-python\npip install tqdm\n\n\n解释:\n\n- 使用 os.walk 遍历目录和子目录中的所有文件。\n- 使用 tqdm 创建进度条,显示文件处理进度。\n- 如果文件的扩展名为 '.avi',则调用 convert_avi_to_mp4 函数进行转换。\n- 转换完成后,使用 os.remove 删除原始的 '.avi' 文件。\n\n注意:\n\n- 请将代码中的 /path/to/directory 替换为实际的目录路径。\n- 确保已经安装了 ffmpeg 和 tqdm 模块。
原文地址: https://www.cveoy.top/t/topic/oWAM 著作权归作者所有。请勿转载和采集!