使用shutil.unpack_archive遇Errno22,如何保留已解压文件或忽略错误?
解决shutil解压Errno 22错误:保留已解压文件/忽略错误继续解压
错误信息翻译:[Errno 22] 参数无效: 'D:\099Logs\HOUJI-10077--UnzipUn7z\bugreport-2023-08-04-141558\bugreport-houji-2023-08-04-141739\lshal-debug\android.frameworks.cameraservice.service@2.0::ICameraService_default.txt'
一、保留已完成解压的文件
你当前的try-except逻辑下,已成功解压的文件已经保留在目标文件夹thirdFolder中。因为shutil.unpack_archive是边解压边写入文件,遇到单个文件错误时不会回滚删除已解压的内容,直接去目标目录即可找到这些文件。
二、忽略错误继续解压
shutil.unpack_archive本身不支持跳过错误文件继续解压,要实现这个功能,需要根据归档类型(zip/7z/tar等)使用对应库逐个提取文件,出错时跳过该文件:
1. 处理Zip归档
使用Python标准库zipfile:
import zipfile import os def unpack_zip_ignore_errors(archive_path, target_dir): os.makedirs(target_dir, exist_ok=True) with zipfile.ZipFile(archive_path, 'r') as zf: for file_info in zf.infolist(): try: zf.extract(file_info, target_dir) print(f"成功解压: {file_info.filename}") except OSError as e: print(f"跳过文件 {file_info.filename},错误: {e}") # 调用示例 unpack_zip_ignore_errors(file, thirdFolder)
2. 处理7z归档
先安装第三方库py7zr:pip install py7zr,再使用以下代码:
import py7zr import os def unpack_7z_ignore_errors(archive_path, target_dir): os.makedirs(target_dir, exist_ok=True) with py7zr.SevenZipFile(archive_path, mode='r') as szf: for name in szf.getnames(): try: szf.extract(targets=[name], path=target_dir) print(f"成功解压: {name}") except OSError as e: print(f"跳过文件 {name},错误: {e}") # 调用示例 unpack_7z_ignore_errors(file, thirdFolder)
3. 处理Tar/Tar.gz等归档
使用Python标准库tarfile:
import tarfile import os def unpack_tar_ignore_errors(archive_path, target_dir): os.makedirs(target_dir, exist_ok=True) with tarfile.open(archive_path, 'r') as tf: for member in tf.getmembers(): try: tf.extract(member, target_dir) print(f"成功解压: {member.name}") except OSError as e: print(f"跳过文件 {member.name},错误: {e}") # 调用示例 unpack_tar_ignore_errors(file, thirdFolder)
4. 自动识别归档类型的通用方法
import os import zipfile import py7zr import tarfile def unpack_any_ignore_errors(archive_path, target_dir): os.makedirs(target_dir, exist_ok=True) if zipfile.is_zipfile(archive_path): unpack_zip_ignore_errors(archive_path, target_dir) elif archive_path.lower().endswith('.7z'): unpack_7z_ignore_errors(archive_path, target_dir) elif tarfile.is_tarfile(archive_path): unpack_tar_ignore_errors(archive_path, target_dir) else: print(f"不支持的归档格式: {archive_path}") # 调用示例 unpack_any_ignore_errors(file, thirdFolder)
内容的提问来源于stack exchange,提问作者Fukai
相关产品推荐
相关产品推荐

