Code2care@Mac % python3 zip_program.py
Traceback (most recent call last):
File "/Users/c2ctech/Desktop/zip_program.py", line 6, in
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/zipfile.py", line 1302, in __init__
self._RealGetContents()
File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/zipfile.py", line 1369, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
You will get a BadZipFile error when you try to unzip a zip file with is either corrupt or not a valid zip file.
Fix:
Try the below options for a fix.
- Make sure that the file you are trying to unzip has a .zip extension.
- If you had downloaded it from the web or a cloud drive, make sure that it was fully downloaded (do a checksum or size check)
- Make sure that the path and the file name provided in your code is correct.
- Try to unzip the file by yourself and see if it works.
When using the zipfile module it is always recommended to wrap your code with try/catch block with and handle zipfile.BadZipFile
import zipfile
zip_file = "data.zip"
extract_fonder = "/user/c2c/prod"
try:
with zipfile.ZipFile(zip_file, 'r') as zip:
zip.extractall(extract_fonder)
print(f"The file {zip_file} was extracted successful!")
except zipfile.BadZipFile:
print(f"An Error occurred while extracting {zip_file} is not a valid ZIP file.")
Referece: https://docs.python.org/3/library/zipfile.html#zipfile.BadZipFile
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!