Fix: zipfile.BadZipFile: File is not a zip file Python


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.

  1. Make sure that the file you are trying to unzip has a .zip extension.
  2. 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)
  3. Make sure that the path and the file name provided in your code is correct.
  4. 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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap