zipfile.BadZipFile
PythonERRORCommonI/O
ZIP file is corrupt or not a valid ZIP
Quick Answer
Catch zipfile.BadZipFile when opening untrusted or downloaded ZIP files; validate the file size and check the magic bytes before opening.
Production Risk
Medium — ZIP extraction from user uploads requires BadZipFile handling.
What this means
Raised by zipfile.ZipFile() when the file is not a valid ZIP archive — corrupted download, truncated file, or wrong file type.
Why it happens
- 1Download was interrupted leaving a truncated file
- 2File is not a ZIP — wrong Content-Type from server
- 3ZIP file was corrupted in transit or storage
Fix
Validate before opening
Validate before opening
import zipfile
import os
def safe_open_zip(path):
if not os.path.exists(path) or os.path.getsize(path) == 0:
raise ValueError(f"File missing or empty: {path}")
try:
return zipfile.ZipFile(path)
except zipfile.BadZipFile as e:
raise ValueError(f"Not a valid ZIP archive: {path}") from eWhy this works
Checking file size before opening catches empty downloads; the try/except wraps the BadZipFile into a domain error with the path.
Code examples
Triggerpython
import zipfile
zipfile.ZipFile('not_a_zip.txt') # BadZipFile: File is not a zip fileTest with is_zipfilepython
if not zipfile.is_zipfile(path):
raise ValueError(f"Not a ZIP: {path}")
with zipfile.ZipFile(path) as zf:
zf.extractall(dest)Same error in other languages
Sources
Official documentation ↗
Python Docs — zipfile module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev