Choose archive formats according to compatibility, metadata and workflow.
How It Works
ZIP is widely supported and convenient for sharing separate files; tar is common for Unix-style directory trees and metadata; gzip is typically a compressed stream, not a collection of named files. Choose based on the recipient and whether preserving permissions is important.
The recipient must have compatible software and should verify the archive before extraction.
Step-by-Step Example
import io
import zipfile
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr("notes/readme.txt", "Project notes")
with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as archive:
print(archive.namelist())
Understanding the Example
- The expression 'io.BytesIO()' supplies the value stored as 'buffer'. This value is then used or checked by the later statements.
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
A successful run of this example prints the following output:
['notes/readme.txt']
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Explain why a shared document bundle might use ZIP while a Unix deployment backup might use tar.gz.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Giving a .gz file to someone expecting a ZIP containing multiple independently named files.
- Assuming every archive format preserves ownership, timestamps and permissions in exactly the same way.
Key Takeaways
- Choose archive formats according to compatibility, metadata and workflow.
- ZIP is widely supported and convenient for sharing separate files; tar is common for Unix-style directory trees and metadata; gzip is typically a compressed stream, not a collection of named files.
- The recipient must have compatible software and should verify the archive before extraction.