Last modified: Feb 10, 2026 By Alexander Williams

Fix BadZipFile: File is Not a Zip File in Python

You try to open a file with Python's zipfile module. An error stops you. The error says "BadZipFile: File is not a zip file". This is a common problem. It happens when Python cannot read your file as a ZIP archive. This guide explains why it happens. It also shows you how to fix it.

What is the BadZipFile Error?

Python's zipfile module works with ZIP files. The BadZipFile error is an exception. It tells you the file is not a valid ZIP archive. The file might be corrupted. It might be in the wrong format. Or it might be empty. Understanding this error is the first step to solving it.

Common Causes of the Error

Several issues can trigger this error. Knowing the cause helps you find the right fix.

1. The File is Not a ZIP Archive

The most obvious cause is simple. You are trying to open a file that is not a ZIP file. You might have the wrong file extension. For example, a .txt or .pdf file renamed to .zip. Python's zipfile module checks the file's magic number. If it's wrong, it raises BadZipFile.

2. The ZIP File is Corrupted

The file might be a ZIP archive that is damaged. This can happen during download. It can happen during file transfer. A corrupted file does not have the proper structure. The zipfile module cannot parse it.

3. The File is Empty or Incomplete

An empty file (0 bytes) cannot be a ZIP archive. A file that was not fully downloaded is also incomplete. Python will see this as an invalid ZIP file.

4. Using the Wrong Mode or Method

You might be using the ZipFile class incorrectly. For example, using read mode ('r') on a file meant for writing. Or using extractall() on a file opened in write mode. This can lead to confusing errors.

How to Diagnose and Fix the Error

Follow these steps to identify and resolve the "BadZipFile" error.

Step 1: Check the File Path and Existence

First, make sure the file exists at the path you provided. Use os.path.exists() to check.


import os

file_path = "my_archive.zip"
if os.path.exists(file_path):
    print("File exists.")
else:
    print("File not found. Check the path.")

File exists.

Step 2: Verify the File is a Valid ZIP

Use the zipfile.is_zipfile() function. This is the best way to check without opening. It returns True or False.


import zipfile

file_path = "my_archive.zip"
if zipfile.is_zipfile(file_path):
    print("File is a valid ZIP archive.")
else:
    print("File is NOT a valid ZIP archive. It may be corrupted or in the wrong format.")

File is NOT a valid ZIP archive. It may be corrupted or in the wrong format.

If this returns False, your file is the problem. You need a new, uncorrupted ZIP file.

Step 3: Open the File with Error Handling

Always use a try-except block when opening ZIP files. This prevents your program from crashing. It also gives you a chance to handle the error gracefully.


import zipfile

file_path = "my_archive.zip"

try:
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        file_list = zip_ref.namelist()
        print(f"ZIP file opened successfully. Contains: {file_list}")
except zipfile.BadZipFile:
    print(f"Error: '{file_path}' is not a valid zip file or is corrupted.")
except FileNotFoundError:
    print(f"Error: File '{file_path}' was not found.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Error: 'my_archive.zip' is not a valid zip file or is corrupted.

Step 4: Check File Size and Integrity

Check the file size. An empty file is a clear sign of a problem. You can also try to download the file again. Network issues often cause incomplete downloads.

Practical Example: Creating and Reading a ZIP File

Let's look at a correct workflow. First, we create a ZIP file using Python. For more on creating archives, see our guide on Python Zip Files: Create, Read, Extract Archives.


import zipfile
import os

# Create some dummy files to zip
with open("document1.txt", "w") as f:
    f.write("Hello from document 1.")
with open("document2.txt", "w") as f:
    f.write("Hello from document 2.")

# Create a new ZIP archive
with zipfile.ZipFile("good_archive.zip", 'w') as zipf:
    zipf.write("document1.txt")
    zipf.write("document2.txt")

print("Created 'good_archive.zip'")

# Now read it back correctly
try:
    with zipfile.ZipFile("good_archive.zip", 'r') as zip_ref:
        print("Contents of the ZIP file:")
        for file_info in zip_ref.infolist():
            print(f"  - {file_info.filename}")
except zipfile.BadZipFile:
    print("This should not happen with a freshly created file.")

# Clean up the dummy files
os.remove("document1.txt")
os.remove("document2.txt")

Created 'good_archive.zip'
Contents of the ZIP file:
  - document1.txt
  - document2.txt

This shows the proper way to handle ZIP files. If you need to work with directories, our article on Python Zip Folder: Compress Directories can help.

Advanced Troubleshooting

If basic checks fail, you might need deeper investigation.

Check File Permissions

Ensure your Python script has read permission for the file. On some systems, permission errors can manifest as cryptic BadZipFile errors.

Binary vs. Text Mode

Never open a ZIP file in text mode ('rt'). ZIP files are binary. The zipfile module handles this internally. But if you pre-open the file, you must use binary mode ('rb').

URL Downloads and BytesIO

When downloading a ZIP file from a URL, you might get the content as bytes. You can use io.BytesIO to treat it as a file-like object for the ZipFile constructor.


import zipfile
import io
import requests

url = "https://example.com/some_archive.zip"
try:
    response = requests.get(url)
    response.raise_for_status()  # Check for HTTP errors

    # Use BytesIO to create a file-like object from bytes
    zip_bytes = io.BytesIO(response.content)

    if zipfile.is_zipfile(zip_bytes):
        with zipfile.ZipFile(zip_bytes, 'r') as zip_ref:
            print("Successfully opened ZIP from URL.")
    else:
        print("Downloaded content is not a valid ZIP file.")
except requests.exceptions.RequestException as e:
    print(f"Failed to download the file: {e}")
except zipfile.BadZipFile:
    print("Downloaded file is corrupted or not a ZIP.")

Conclusion

The "BadZipFile: File is not a zip file" error is a clear message. Your file is not a valid ZIP archive. The solution involves careful checking. Always verify the file exists. Use zipfile.is_zipfile() to test its validity. Wrap your ZipFile operations in try-except blocks. This protects your program. It also provides better error messages for users.

Remember, the zipfile module is powerful. It is also strict about file format. For related iteration techniques, you might explore the Python Zip Function: Iterate Over Lists. By following the steps in this guide, you can quickly diagnose and fix this common Python error. You will be back to working with your archives in no time.