Python 3.6 Zipfile Backport
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
- breaking Pickling `zipfile.ZipFile` instances will raise a `TypeError` in Python 3.6+ (and by extension, when using `zipfile36`). This behavior change fixed a prior bug in Python < 3.6 where `ZipFile` objects containing unpicklable `_thread.RLock` objects were incorrectly picklable. Code relying on pickling `ZipFile` objects for serialization will break.
- gotcha The `zipfile.is_zipfile()` function is not a robust file type identifier and can produce false positives. It primarily checks for the presence of a ZIP central directory signature at the end of a file, which can coincidentally appear in other file types (e.g., gzipped files, executables with appended data).
- breaking Error types for certain operations changed in Python 3.6. Specifically, operations on a closed `ZipFile` (e.g., `open()`, `write()`, `extract()`, `extractall()`, `writestr()`) or with an invalid mode will now raise `ValueError` instead of `RuntimeError`.
- deprecated The `mode='U'` option for `ZipFile.open()` (for universal newlines mode) was removed in Python 3.6.
Install
-
pip install zipfile36
Imports
- zipfile
import sys if sys.version_info >= (3, 6): import zipfile else: import zipfile36 as zipfile
Quickstart
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.")