gzip.
How It Works
gzip.open(filename, mode="rt" or "wb") reads or writes gzip-compressed data. Specify text encoding for text modes; gzip is compression, not encryption, and generally stores one compressed byte stream rather than a folder of files.
Step-by-Step Example
import gzip
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as temporary_directory:
compressed_path = Path(temporary_directory) / 'notes.txt.gz'
with gzip.open(compressed_path, 'wt', encoding='utf-8') as destination:
destination.write('Résumé completed')
with gzip.open(compressed_path, 'rt', encoding='utf-8') as source:
print(source.read())
Understanding the Example
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
- The expression "Path(temporary_directory) / 'notes.txt.gz'" supplies the value stored as 'compressed_path'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
Résumé completed
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
Write a UTF-8 note to a gzip file and read it back.
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
- Opening binary gzip output as Unicode text or forgetting that gzip files contain data, not directory structures.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- gzip.
- gzip.open(filename, mode="rt" or "wb") reads or writes gzip-compressed data.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.