如何用try捕获BadZipFile异常实现CelebA数据集循环下载不中断
解决CelebA下载时BadZipFile异常捕获失效问题
你的代码存在3个核心问题:
- 未显式导入
BadZipFile类,Python无法识别该异常类型 CelebA调用语句缺少闭合括号,属于语法错误- 缺失
time库导入,sleep方法无法调用
正确实现代码
import time from zipfile import BadZipFile import torchvision.datasets as datasets # 替换为你的实际存储路径 path_to_download = "./celebA_data" max_retry = 100 for i in range(max_retry): try: datasets.CelebA( root=path_to_download, split='train', download=True ) # 下载成功直接跳出循环,无需继续重试 print("数据集下载完成") break except BadZipFile: print(f"第{i+1}次下载出错,压缩包损坏,4秒后重试") time.sleep(4) else: # 循环走完100次都未成功时触发 print(f"重试{max_retry}次后仍下载失败,请检查网络连接或手动下载数据集")
异常捕获不到的排查方案
如果按上述写法还是无法捕获异常,说明torchvision内部对BadZipFile做了二次包装,可先运行以下代码打印实际抛出的异常类型:
try: datasets.CelebA(root=path_to_download, split='train', download=True) except Exception as e: print(type(e)) print(e)
将打印出的异常类替换到except后的捕获位置即可。
内容的提问来源于stack exchange,提问作者Lucian
相关产品推荐
相关产品推荐

