Python 3.6 Zipfile Backport

0.1.3 · maintenance · verified Sun Apr 12

zipfile36 is a backport of the `zipfile` module from Python 3.6, offering enhancements and API changes introduced in that version to older Python environments. Its latest version is 0.1.3, released in October 2016. As a backport for an End-of-Life Python version (3.6), the library is considered to be in maintenance status with no active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `zipfile36` (aliased as `zipfile`) to create a ZIP archive, add a file to it, and then read the file's contents from the archive. It includes the recommended conditional import statement.

import sys
import os
import io

# Suggested usage for zipfile36 backport
if sys.version_info >= (3, 6):
    import zipfile
else:
    try:
        import zipfile36 as zipfile
    except ImportError:
        print("zipfile36 not installed. Please install with 'pip install zipfile36' for Python versions < 3.6.")
        sys.exit(1)

# Create a dummy file
file_content = "Hello, zipfile36! This is a test file."
file_name = "test_file.txt"
with open(file_name, "w") as f:
    f.write(file_content)

zip_file_name = "my_archive.zip"

# 1. Create a zip archive and add a file
print(f"Creating '{zip_file_name}' and adding '{file_name}'...")
with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) as zf:
    zf.write(file_name, arcname="docs/zipped_test_file.txt")
print(f"'{file_name}' added to '{zip_file_name}' as 'docs/zipped_test_file.txt'.")

# 2. Read from the zip archive
print(f"\nReading contents from '{zip_file_name}'...")
with zipfile.ZipFile(zip_file_name, 'r') as zf:
    print(f"Files in '{zip_file_name}': {zf.namelist()}")
    with zf.open("docs/zipped_test_file.txt") as member_file:
        read_content = member_file.read().decode('utf-8')
        print(f"Content of 'docs/zipped_test_file.txt': {read_content}")

# Clean up
os.remove(file_name)
os.remove(zip_file_name)
print("\nCleaned up dummy files.")

view raw JSON →