# How to Fix Python zipimport.ZipImportError

The zipimport.ZipImportError occurs when Python fails to import a module from a ZIP archive. This error typically happens when working with .egg files, zip applications (__main__.py in a zip), or compressed package distributions.

Error Patterns

Basic ZipImportError

text
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    import mymodule
zipimport.ZipImportError: can't decompress data; zlib not available

Invalid Zip Structure

text
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    from package import module
zipimport.ZipImportError: bad local file header

Missing __init__.py in Zip

text
Traceback (most recent call last):
  File "run.py", line 3, in <module>
    import mypackage
zipimport.ZipImportError: not a package

Compressed Data Error

text
Traceback (most recent call last):
  File "app.py", line 4, in <module>
    import compressed_module
zipimport.ZipImportError: can't decompress data for 'compressed_module.pyc'

Common Causes

  1. 1.zlib not available - Python built without zlib compression support
  2. 2.Corrupted zip file - Archive has invalid structure or is damaged
  3. 3.Wrong compression method - Zip uses unsupported compression (e.g., LZMA)
  4. 4.Missing package marker - No __init__.py in package directory within zip
  5. 5.Path configuration issue - Zip file not in Python's import path
  6. 6.Zip file not readable - Permission or file access issues
  7. 7.Mixed content types - Source and compiled files mismatched

Diagnosis Steps

Step 1: Verify zlib is Available

```python import sys

print(f"Python executable: {sys.executable}") print(f"zlib available: {'zlib' in sys.modules or __import__('zlib') is not None}")

# Try importing zlib try: import zlib print(f"zlib version: {zlib.__version__}") except ImportError: print("zlib is NOT available - this is the problem!") ```

Step 2: Check Zip File Integrity

```python import zipfile import os

zip_path = "mypackage.zip"

# Check if file exists print(f"File exists: {os.path.exists(zip_path)}")

# Check if it's a valid zip try: with zipfile.ZipFile(zip_path, 'r') as zf: print(f"Valid zip file: True") print(f"Compression type: {zf.compression}") print(f"Contents:") for name in zf.namelist(): info = zf.getinfo(name) print(f" {name}: compress_type={info.compress_type}, size={info.file_size}")

# Test integrity bad_file = zf.testzip() if bad_file: print(f"Corrupted file: {bad_file}") else: print("All files OK") except zipfile.BadZipFile as e: print(f"Invalid zip file: {e}") except Exception as e: print(f"Error: {e}") ```

Step 3: Check Import Path Configuration

```python import sys

print("Python import path:") for path in sys.path: print(f" {path}")

# Check if zip is in path zip_path = "/path/to/mypackage.zip" print(f"\nZip in path: {zip_path in sys.path}")

# Check if it's a zipimporter path for importer in sys.path_hooks: print(f"Path hook: {importer}") ```

Step 4: Verify Zip Contents Structure

```python import zipfile

def inspect_zip_structure(zip_path): """Check if zip has proper Python package structure.""" with zipfile.ZipFile(zip_path, 'r') as zf: files = zf.namelist()

# Check for __init__.py init_files = [f for f in files if f.endswith('__init__.py')] print(f"__init__.py files: {init_files}")

# Check for .py files py_files = [f for f in files if f.endswith('.py')] print(f"Python files: {py_files}")

# Check for .pyc files pyc_files = [f for f in files if f.endswith('.pyc')] print(f"Compiled files: {pyc_files}")

# Check directory structure dirs = set() for f in files: parts = f.split('/') for i in range(len(parts) - 1): dirs.add('/'.join(parts[:i+1])) print(f"Directories: {sorted(dirs)}")

inspect_zip_structure("package.zip") ```

Solutions

Solution 1: Ensure zlib is Available

```bash # Check if Python was built with zlib python -c "import zlib; print(zlib.__version__)"

# If zlib is missing, reinstall Python with zlib support # Ubuntu/Debian sudo apt-get install zlib1g-dev # Then rebuild Python or reinstall

# macOS (Homebrew) brew install zlib brew reinstall python

# Windows - zlib is usually included in standard Python # If missing, reinstall Python from python.org ```

```python # Alternative: Check system zlib import ctypes import sys

if sys.platform == 'linux': try: libz = ctypes.CDLL('libz.so.1') print("System zlib available") except OSError: print("System zlib NOT found - install zlib1g-dev") ```

Solution 2: Fix Corrupted Zip File

```python import zipfile import os

def repair_zip(zip_path): """Attempt to repair a corrupted zip file.""" # Try to read and verify try: with zipfile.ZipFile(zip_path, 'r') as zf: bad_file = zf.testzip() if bad_file: print(f"First corrupted file: {bad_file}") # Try to extract good files good_files = [f for f in zf.namelist() if f != bad_file]

# Create new zip with good files new_path = zip_path + '.repaired' with zipfile.ZipFile(new_path, 'w') as new_zf: for name in good_files: try: data = zf.read(name) new_zf.writestr(name, data) except: print(f"Could not recover: {name}")

print(f"Created repaired zip: {new_path}") return new_path else: print("Zip appears valid") return zip_path except zipfile.BadZipFile: print("Zip is completely corrupted") return None ```

Solution 3: Use Correct Compression Method

```python import zipfile

# Problem: Zip uses unsupported compression (LZMA, BZIP2) # Python zipimport only supports ZIP_STORED (no compression) and ZIP_DEFLATED (zlib)

def create_importable_zip(source_dir, output_zip): """Create a zip file compatible with zipimport.""" with zipfile.ZipFile(output_zip, 'w', compression=zipfile.ZIP_DEFLATED) as zf: for root, dirs, files in os.walk(source_dir): for file in files: if file.endswith('.py') or file.endswith('.pyc'): full_path = os.path.join(root, file) arcname = os.path.relpath(full_path, source_dir) zf.write(full_path, arcname)

print(f"Created importable zip: {output_zip}")

# Or use no compression (ZIP_STORED) for maximum compatibility with zipfile.ZipFile('package.zip', 'w', zipfile.ZIP_STORED) as zf: zf.write('mymodule.py') ```

Solution 4: Add __init__.py to Package in Zip

```python import zipfile import os

def fix_package_zip(zip_path, package_name): """Add __init__.py if missing in zip package.""" with zipfile.ZipFile(zip_path, 'a') as zf: # 'a' for append # Check if __init__.py exists init_path = f"{package_name}/__init__.py"

if init_path not in zf.namelist(): # Add empty __init__.py zf.writestr(init_path, "# Package marker\n") print(f"Added {init_path} to zip") else: print("__init__.py already exists")

fix_package_zip('mypackage.zip', 'mypackage') ```

Solution 5: Add Zip to Python Path

```python import sys import os

# Problem: Zip not in sys.path zip_path = "/path/to/mypackage.zip"

# Solution: Add to sys.path before importing if os.path.exists(zip_path): sys.path.insert(0, zip_path) import mypackage # Now works else: print(f"Zip file not found: {zip_path}")

# Or use site-packages import site site.addsitedir("/path/to/zips") ```

Solution 6: Rebuild Egg Files

```bash # Problem: Old .egg files from setuptools may be corrupted # Solution: Rebuild from source

# Remove old egg pip uninstall package_name

# Reinstall pip install package_name --force-reinstall

# Or build from source python setup.py bdist_egg ```

```python # Check egg file structure import zipfile

def check_egg(egg_path): """Verify .egg file is valid.""" try: with zipfile.ZipFile(egg_path) as zf: # EGG-INFO directory should exist egg_info = [f for f in zf.namelist() if 'EGG-INFO' in f] print(f"EGG-INFO files: {egg_info}")

# PKG-INFO should exist if 'EGG-INFO/PKG-INFO' in zf.namelist(): pkg_info = zf.read('EGG-INFO/PKG-INFO').decode() print(f"Package info:\n{pkg_info[:200]}...")

return zf.testzip() is None except: return False ```

Solution 7: Create Zip Application Correctly

```python import zipfile import os

def create_zip_app(source_dir, output_zip): """Create a runnable zip application (__main__.py in zip).""" with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zf: # Add __main__.py as entry point main_content = ''' import sys import os

def main(): print("Zip application running!") # Your application code here

if __name__ == "__main__": main() ''' zf.writestr('__main__.py', main_content)

# Add other modules for root, dirs, files in os.walk(source_dir): for file in files: if file.endswith('.py'): full_path = os.path.join(root, file) arcname = os.path.relpath(full_path, source_dir) zf.write(full_path, arcname)

print(f"Created zip app: {output_zip}") print(f"Run with: python {output_zip}")

# Run the zip application # python myapp.zip ```

Solution 8: Handle Shutil.make_archive Issues

```python import shutil import zipfile

# Problem: shutil.make_archive may use wrong compression shutil.make_archive('package', 'zip', 'src') # Might use ZIP_STORED

# Solution: Use zipfile directly with correct compression def make_importable_archive(name, source_dir): """Create importable zip archive.""" output = f"{name}.zip"

with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as zf: for root, dirs, files in os.walk(source_dir): for file in files: full_path = os.path.join(root, file) arcname = os.path.relpath(full_path, source_dir) zf.write(full_path, arcname)

return output ```

Working with Zip Imports

Debug Zip Import Process

```python import sys import zipimport

def debug_zip_import(zip_path, module_name): """Debug the zip import process.""" print(f"Attempting to import {module_name} from {zip_path}")

# Create zipimporter try: importer = zipimport.zipimporter(zip_path) print(f"Zipimporter created successfully")

# Check if module can be found try: code = importer.get_code(module_name) print(f"Module code found: {code}") except zipimport.ZipImportError as e: print(f"Module not found in zip: {e}")

# Try actual import try: module = importer.load_module(module_name) print(f"Module loaded: {module}") except zipimport.ZipImportError as e: print(f"Load failed: {e}")

except zipimport.ZipImportError as e: print(f"Cannot create zipimporter: {e}")

debug_zip_import("package.zip", "mymodule") ```

Extract and Import from Problematic Zip

```python import zipfile import tempfile import sys import os

def extract_and_import(zip_path, module_name): """Extract module from zip and import from extracted location.""" # Create temp directory temp_dir = tempfile.mkdtemp()

try: # Extract from zip with zipfile.ZipFile(zip_path) as zf: zf.extractall(temp_dir)

# Add to path and import sys.path.insert(0, temp_dir) module = __import__(module_name)

return module finally: # Cleanup sys.path.remove(temp_dir) # Note: module remains in sys.modules

module = extract_and_import("problematic.zip", "mymodule") ```

Prevention Tips

  1. 1.Use ZIP_DEFLATED compression - Maximum compatibility with Python
  2. 2.Include __init__.py - Required for package imports from zip
  3. 3.Verify zlib is available - Before distributing zip packages
  4. 4.Test zip integrity - Before deployment with testzip()
  5. 5.Include both .py and .pyc - For version compatibility

```python # Good pattern: Create importable zip import zipfile import os

def create_package_zip(source_dir, output_path): """Create a properly structured importable zip.""" with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf: for root, dirs, files in os.walk(source_dir): # Ensure __init__.py exists for each package if files and any(f.endswith('.py') for f in files): init_path = os.path.join(root, '__init__.py') if not os.path.exists(init_path): # Create empty init arcname = os.path.relpath(os.path.join(root, '__init__.py'), source_dir) zf.writestr(arcname, '')

for file in files: if file.endswith('.py') or file.endswith('.pyc'): full_path = os.path.join(root, file) arcname = os.path.relpath(full_path, source_dir) zf.write(full_path, arcname)

# Verify if zf.testzip(): raise ValueError("Created zip has errors")

return output_path ```

  • ImportError - General import failure
  • ModuleNotFoundError - Module not in any path
  • zipfile.BadZipFile - Invalid zip file structure
  • OSError - File system issues with zip