Separate the idea of packing multiple files from reducing the bytes they occupy.
How It Works
An archive bundles files and directory names, while compression reduces representation size using an algorithm. A ZIP can do both; TAR principally bundles entries and can be combined with gzip or another compressor. Already-compressed files may show little size reduction.
Archiving also stores names and metadata; compression ratio does not tell you whether archive extraction is safe.
Step-by-Step Example
import io
import tarfile
import gzip
payload = b"repeated message\n" * 40
compressed = gzip.compress(payload)
print(len(compressed) < len(payload))
with tarfile.open(fileobj=io.BytesIO(), mode="w") as archive:
entry = tarfile.TarInfo("notes.txt")
entry.size = len(payload)
archive.addfile(entry, io.BytesIO(payload))
Understanding the Example
- The expression 'b"repeated message\\n" * 40' supplies the value stored as 'payload'. This value is then used or checked by the later statements.
- The expression 'gzip.compress(payload)' supplies the value stored as 'compressed'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
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
Compare the sizes of plain text, its gzip representation and a TAR archive containing that text.
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
- Assuming a .tar file must be compressed because it is an archive.
- Expecting JPEG or ZIP data to become substantially smaller with another compression pass.
Key Takeaways
- Separate the idea of packing multiple files from reducing the bytes they occupy.
- An archive bundles files and directory names, while compression reduces representation size using an algorithm.
- Archiving also stores names and metadata; compression ratio does not tell you whether archive extraction is safe.