在Google Colab中用rarfile创建RAR压缩包遇NotImplementedError求助
问题解决:无法用rarfile创建RAR压缩包
错误原因
rarfile库仅支持**读取(mode=r)**RAR文件,不提供创建/写入RAR压缩包的功能——这是因为RAR是专有格式,该库未实现写入逻辑,所以调用mode="w"会触发NotImplementedError。
解决方案
方案1:使用系统rar命令行工具生成RAR包(推荐)
Colab默认未安装rar工具,先执行安装命令,再通过Python调用系统命令完成压缩:
- 安装rar工具:
!apt-get install -y rar
- 修改后的Python代码:
import os import subprocess current_directory = os.getcwd() for folder in os.listdir(current_directory): folder_path = os.path.join(current_directory, folder) # 仅处理文件夹,跳过文件 if not os.path.isdir(folder_path): continue # 调用rar命令递归压缩文件夹 rar_output = os.path.join(current_directory, f"{folder}.rar") subprocess.run(["rar", "a", "-r", rar_output, folder_path], check=True) print("所有文件夹已完成RAR压缩。")
参数说明:rar a表示创建/添加到压缩包,-r表示递归包含子文件夹。
方案2:改用ZIP格式(无需额外依赖)
如果不需要强制生成RAR格式,Python自带的zipfile库支持写入压缩包,代码修改如下:
import os import zipfile current_directory = os.getcwd() for folder in os.listdir(current_directory): folder_path = os.path.join(current_directory, folder) if not os.path.isdir(folder_path): continue zip_output = os.path.join(current_directory, f"{folder}.zip") # 使用压缩模式创建ZIP包 with zipfile.ZipFile(zip_output, "w", zipfile.ZIP_DEFLATED) as archive: # 递归遍历文件夹内所有文件 for root, dirs, files in os.walk(folder_path): for file in files: file_full_path = os.path.join(root, file) # 保存相对路径,避免归档内出现完整系统路径 archive_path = os.path.relpath(file_full_path, current_directory) archive.write(file_full_path, archive_path) print("所有文件夹已完成ZIP压缩。")
内容的提问来源于stack exchange,提问作者Peter Long
相关产品推荐
相关产品推荐

